2015-06-06 57 views
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 
+3

它是一個簡單的'rowSums'操作。你想爲'dataset'或'y'中的每個單詞添加一列嗎? –

+0

我只想爲每個單詞列如上所示。但我有一大堆像V1:V100這樣的變量,我需要創建像玉米,餐等列 – user3570187

+0

我得到這個錯誤。錯誤在rowSums(數據集,na.rm = FALSE,dims = 1):'x'必須是數字 – user3570187

回答

4

使用rowSums的選項。我們創建一個名稱向量進行比較,然後根據該名稱創建列。

v1 <- c('corn', 'meal')  
dataset[v1] <- sapply(v1, function(x) rowSums(dataset[-1]==x)) 
相關問題