2017-05-26 61 views
-2

「」「我需要向數據框x添加一列,指示y的元素出現在」動物「列中的次數X: 「」」我需要計算y的元素出現在x的元素中使用R的次數:

library(stringr) 

x <- data_frame(c("cat", "dog", "cat and dog")) 
colnames(x) <- "animal" 
x$count <- 0 

y <- data_frame(c("cat", "dog")) 
colnames(y) <- "animals" 

for (j in length(y$animals)){ 
    for (i in length(x$animal)){ 
    if(str_detect(x$animal[i],y$animals[j])==TRUE){ 
     x$count[i] = x$count[i] + 1 
    } 
    } 
} 

「」 「X中的計數列應改爲1,1,2」 「」

+0

'str_count'是'stringr'中的一個函數我相信。無需循環 – thelatemail

+0

只需'str_count(x $ animal,paste(y $ animals,collapse ='|'))' – Sotos

回答

0

grepl該函數返回一個可以概括的邏輯值。 sapply是一個循環的R等價物:

x$count <- sapply(x$animal, 
         function(z){ sum(sapply(y$animals, 
              function(zz){ grepl(zz, z)}))}) 
> x 
# A tibble: 3 x 2 
     animal count 
     <chr> <int> 
1   cat  1 
2   dog  1 
3 cat and dog  2 
相關問題