在画框中
data.frame(stocknum = c(1,2,3), col1 = c("my text here", "another one", "one more final text"))如何检测单词" text“和"final”是否存在于col1列的每一行中,如果文本中存在,则创建一个新列;如果不存在,则创建0列
输出示例:
data.frame(stocknum = c(1,2,3), col1 = c("my text here", "another one", "one more final text"), text = c(1,0,1), final = c(0,0,1))发布于 2020-12-08 01:30:25
仅使用base R和apply()
#Data
df <- data.frame(stocknum = c(1,2,3), col1 = c("my text here", "another one", "one more final text"))
#Code
df$text <- apply(df['col1'],1,function(x) as.numeric(length(which(grepl('text',x)))>=1))
df$final <- apply(df['col1'],1,function(x) as.numeric(length(which(grepl('final',x)))>=1))输出:
df
stocknum col1 text final
1 1 my text here 1 0
2 2 another one 0 0
3 3 one more final text 1 1https://stackoverflow.com/questions/65186218
复制相似问题