給定一個數據框,我想在我的一列上使用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
使用它。我想知道是否有替代方案。會說話的棍子是你的:)
編輯示例以闡明所需輸出 – madmaxthc
使用'testdf $ col3 < - sapply(strsplit(testdf $ col1,split ='\\。'),\'[''1)' – MrFlick
'tidyr :: separate' – HubertL