【问题标题】:I need to count how many times elements of y appear in elements of x using R:我需要使用 R 计算 y 的元素出现在 x 的元素中的次数:
【发布时间】: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 = '|'))

标签: r for-loop stringr


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2018-10-19
    • 1970-01-01
    • 2022-11-30
    • 2012-06-11
    • 2020-06-09
    • 2020-02-04
    相关资源
    最近更新 更多