3

我正在尝试从数据框中符合某些条件的行中提取所有字符串,例如每行中有多少单词匹配“玉米”。这是输入。

install.packages('stringr')
library(stringr)
dataset <- c("corn", "cornmeal", "corn on the cob", "meal")
y<- c('corn',"corn","mean","meal")
id<- c(1,2,3,4)
dataset <- data.frame(id,dataset,y)

id         dataset    y
1  1            corn corn
2  2        cornmeal corn
3  3 corn on the cob mean
4  4            meal meal

我正在尝试获得这样的输出

 id         dataset    y    corn  meal 
  1  1            corn corn  2     0 
  2  2        cornmeal corn  1     0
  3  3 corn on the cob mean  0     0
  4  4            meal meal  0     2
4

1 回答 1

4

使用rowSums. 我们创建一个名称向量进行比较,然后根据该名称创建列。

v1 <- c('corn', 'meal')     
dataset[v1] <- sapply(v1, function(x)  rowSums(dataset[-1]==x))
于 2015-06-06T20:06:24.867 回答