计算 table 中连续向量的元素
Counting elements of a vector in a row in the table
我有以下问题。假设我在数据框中有一列,一列中的值是向量,对于每一行数据,我想计算该特定向量中的元素数量,例如
ID, brands
1, c("brand1", "brand2", "brand3")
2, c("brand4")
3, c("brand5", "brand7")
并使用 dplyr 我想添加 'counter' 列,它告诉我行中有多少元素具有特定向量,例如
ID, brands, counter
1, c("brand1", "brand2", "brand3"), 3
2, c("brand4"), 1
3, c("brand5", "brand7"), 2
我使用了 counter = length(brands)
但它给出了框架中的总行数。
使用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
我有以下问题。假设我在数据框中有一列,一列中的值是向量,对于每一行数据,我想计算该特定向量中的元素数量,例如
ID, brands
1, c("brand1", "brand2", "brand3")
2, c("brand4")
3, c("brand5", "brand7")
并使用 dplyr 我想添加 'counter' 列,它告诉我行中有多少元素具有特定向量,例如
ID, brands, counter
1, c("brand1", "brand2", "brand3"), 3
2, c("brand4"), 1
3, c("brand5", "brand7"), 2
我使用了 counter = length(brands)
但它给出了框架中的总行数。
使用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