2017-04-13 34 views
0

給定一個數據框,我想在我的一列上使用strsplit,並返回矢量的第一個元素。這裏是例子:如何子集一個sapply函數輸出

testdf<- data.frame(col1= c('string1.string2', 'string3.string4'), 
        col2= c('somevalue', 'someothervalue'), 
        stringsAsFactors = FALSE) 

我要生成一個新的列如 testdf$col3 <- c('string1', 'string3')

我試過如下:

testdf$col3<- strsplit(testdf$col1, split = '\\.')[[1]])[1] 

其中,當然,不能正常工作。它僅返回輸出的第一個元素('string1')並將其寫入整個列。 一個解決辦法是寫一個自定義函數:

customfx<- function(ind_cell){ 
my_out<- strsplit(ind_cell, split = '\\.')[[1]][1] 
return(my_out)} 

然後用sapply使用它。我想知道是否有替代方案。會說話的棍子是你的:)

+0

編輯示例以闡明所需輸出 – madmaxthc

+1

使用'testdf $ col3 < - sapply(strsplit(testdf $ col1,split ='\\。'),\'[''1)' – MrFlick

+1

'tidyr :: separate' – HubertL

回答

2

您可以使用sub(這是矢量)與正則表達式此:

testdf$col3 <- sub("^([^.]+).*", "\\1", testdf$col1) 

testdf 
#    col1   col2 col3 
#1 string1.string2  somevalue string1 
#2 string3.string4 someothervalue string3 

這裏使用^([^.]+).*整個字符串匹配和捕獲從一開始直到子滿足一個點,然後用反向引用替換整個字符串與捕獲的組。

+1

我很感謝你加入解釋,這是我經常需要的東西:) – madmaxthc

相關問題