0

I have the following problem. Suppose I have a column in the data frame, the values in one column are vectors and for each row of data I would like to count the number of elements in that particular vector, eg.

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

and using dplyr I would like to add 'counter' column which tells me how many elements has particular vector in the row, eg.

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

I used counter = length(brands) but it gives the total number of rows in the frame.

Heikki
  • 2,178
  • 15
  • 29
krakowi
  • 539
  • 4
  • 16

1 Answers1

3

Use lengths instead of 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
lukeA
  • 50,755
  • 5
  • 83
  • 91