给定一个数据帧,我想在我的一个列上使用strsplit
,并返回向量的第一个元素。这是一个例子:
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]
当然,它不起作用。它只返回输出的第一个元素(&#39; string1&#39;)并将其写入整个列。 一种解决方案是编写自定义函数:
customfx<- function(ind_cell){
my_out<- strsplit(ind_cell, split = '\\.')[[1]][1]
return(my_out)}
然后将其与sapply
一起使用。我想知道是否有替代方案。说话棒是你的:))
答案 0 :(得分:2)
您可以使用正则表达式 sub
(矢量化):
testdf$col3 <- sub("^([^.]+).*", "\\1", testdf$col1)
testdf
# col1 col2 col3
#1 string1.string2 somevalue string1
#2 string3.string4 someothervalue string3
这里使用^([^.]+).*
匹配整个字符串并从开头捕获子字符串直到满足点,然后使用后引用将整个字符串替换为捕获的组。