【问题标题】:Counting elements of a vector in a row in the table计算表中一行中向量的元素
【发布时间】:2018-05-03 14:07:27
【问题描述】:

我有以下问题。假设我在数据框中有一列,一列中的值是向量,对于每一行数据,我想计算该特定向量中元素的数量,例如。

ID, brands
1, c("brand1", "brand2", "brand3")
2, c("brand4")
3, c("brand5", "brand7")

并使用 dplyr 我想添加“计数器”列,它告诉我行中有多少元素具有特定向量,例如。

ID, brands, counter
1, c("brand1", "brand2", "brand3"), 3
2, c("brand4"), 1
3, c("brand5", "brand7"), 2

我使用了counter = length(brands),但它给出了框架中的总行数。

【问题讨论】:

  • 请使用dput() 提供可重现的数据示例,如here 所述
  • dplyr::n_distinct(brands) ?
  • 用于数据 - df <- data.table(ID = c(1,2,3), brands = c(c('brand1, brand2, brand3'), c('brand4'), c('brand5, brand7')))
  • n_distinct(brands) 返回总行数,与lenght(brands) 的结果相同

标签: r vector dplyr counter


【解决方案1】:

使用lengths 代替length

df <- data.frame(
  ID=1:3, 
  brands=I(list(
    c("brand1", "brand2", "brand3"),
    c("brand4"),
    c("brand5", "brand7")
  ))
)
df$n <- lengths(df$brands)           
df
# ID       brands n
# 1  1 brand1, .... 3
# 2  2       brand4 1
# 3  3 brand5, .... 2

【讨论】:

  • @J_F,什么 cmets? OP 似乎有一个列表列
  • 谢谢!这正是我想要的。
猜你喜欢
  • 2014-02-27
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2021-07-01
  • 2015-02-11
  • 1970-01-01
  • 2021-12-10
  • 2019-04-19
相关资源
最近更新 更多