'Counting elements of a vector in a row in the table

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lukeA