Reputation: 44638
A handy trick (especially for stat testing) is to convert a wide data.frame to a long data.frame with embedded lists.
df <- data.frame(
A = sample(c(1:10),1000,replace = TRUE),
B = sample(c(1:10),1000,replace = TRUE),
C = sample(c(1:10),1000,replace = TRUE)) %>%
gather %>% group_by(key) %>%
summarize(response_list = list(value))
Given a data.frame with an embedded list, how do I append summary counts for each of the embedded lists so that the data.frame looks like this:
key response_list 1 2 3 4 5 6 7 8 9 10
A list() x x x x x x x x x x
...
where, x, is a respective count of the occurrence of each number in the embedded list (akin to table(factor(the_list())
)
Upvotes: 0
Views: 56
Reputation: 28441
df <- cbind(df, do.call(rbind, lapply(df$response_list, table)))
tbl_df(df)
# Source: local data frame [3 x 12]
#
# key response_list 1 2 3 4 5 6 7 8 9 10
# (fctr) (chr) (int) (int) (int) (int) (int) (int) (int) (int) (int) (int)
# 1 A <int[1000]> 97 105 97 100 103 103 86 101 90 118
# 2 B <int[1000]> 98 100 108 92 115 87 101 105 98 96
# 3 C <int[1000]> 109 97 87 92 91 90 114 109 104 107
Upvotes: 3