[英]Split list column into multiple integer columns on R dataframe
I have an R dataframe with 2 columns: ID of the transaction, and a list of products associated我有一个包含 2 列的 R 数据框:交易 ID 和相关产品列表
I need a dataset that have the same number of rows (a row per transaction), a number of columns equal to all possible products with values from 0 to n depending on how many times the transaction contains that product我需要一个具有相同行数(每笔交易一行)的数据集,列数等于所有可能的产品,其值从 0 到 n 取决于交易包含该产品的次数
Is there a quick way to do this?有没有快速的方法来做到这一点?
Reproducible example可重现的例子
Input输入
tibble(ID = c('01', '02'),
Products = list(c('Apple', 'Apple', 'Orange'), c('Pear')))
Output输出
tibble(ID = c('01', '02'),
Apple = c(2, 0),
Orange = c(1, 0),
Pear = c(0, 1))
# A tibble: 2 x 4
ID Apple Orange Pear
<chr> <dbl> <dbl> <dbl>
1 01 2 1 0
2 02 0 0 1
You can do this with unnest_longer
from tidyr
.您可以使用
unnest_longer
的tidyr
执行此tidyr
。 Try this:尝试这个:
library(dplyr)
library(tidyr)
tibble(ID = c('01', '02'),
Products = list(c('Apple', 'Apple', 'Orange'), c('Pear'))) %>%
unnest_longer(Products) %>%
count(ID, Products) %>%
spread(Products, n, fill = 0)
#> # A tibble: 2 x 4
#> # Groups: ID [2]
#> ID Apple Orange Pear
#> <chr> <dbl> <dbl> <dbl>
#> 1 01 2 1 0
#> 2 02 0 0 1
Created on 2020-03-10 by the reprex package (v0.3.0)由reprex 包(v0.3.0) 于 2020 年 3 月 10 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.