-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」 「」
'str_count'是'stringr'中的一個函數我相信。無需循環 – thelatemail
只需'str_count(x $ animal,paste(y $ animals,collapse ='|'))' – Sotos