【发布时间】:2017-05-26 23:58:59
【问题描述】:
"""我需要在dataframe x中添加一列,表示y的元素出现在x的"animal"列中的次数:"""
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中的一个函数,我相信。无需循环 -
只需
str_count(x$animal, paste(y$animals, collapse = '|'))