首页 > 解决方案 > 定义列中的展开()

问题描述

基本上,对于每个 id,我都有一组产品 id,并且我试图将它们分布在一组定义列中。每个 id 只能有 5 个 product_id。前任:

id product_id 
1   305
1   402
2   200
1   305
3   402
3   402

所以我以二进制结果传播,例如:

id 305 402 200 
1   2   0   0
2   0   0   1
3   0   2   0

但我想:

id  product1  product2 product3 product4... until 5 
1      305      305       0
2      200      0         0
3      402      402       0

如果有人有干净的东西(我有大约 10K 行)那就太棒了!谢谢!

#this gives me the binary outcome
for (i in names(test2[2:18])) {
  test2$product1[test2[i] == 1 ] <- i
  }

#this is a try to iterate through each row but it s pretty bad

    for(i in 1:nrow(test2)){
  if(test2[i,1]== 1){

    test2$product1[i] <- colnames(test2[1])
  } else if(test2[i,1]==2){

    test2$product1[i] <- colnames(test2[1])
    test2$product2[i] <- colnames(test2[1])
  } else if(test2[i,1]==3){

    test2$product1[i] <- colnames(test2[1])
    test2$product2[i] <- colnames(test2[1])
    test2$product3[i] <- colnames(test2[1])
  } else if(test2[i,1]==4){

and so one...

预期的:

id  product1  product2 product3 product4... until 5 
1      305      305       0
2      200      0         0
3      402      402       0

实际的:

id 305 402 200 
1   2   0   0
2   0   0   1
3   0   2   0

标签: r

解决方案


我们可以通过 'id' 创建一个序列列,然后spread. 请注意,简单spread的 ing 直到 5 才会包含所有“产品”,因为数据中缺少这些。为了做到这一点,将序列创建为factorlevels“product1”到“product5”指定的序列,并在 中spread指定drop = FALSE不丢弃未使用的序列levels

library(tidyverse)
df1 %>% 
   group_by(id) %>%
   mutate(product = factor(paste0('product', row_number()), 
             levels = paste0('product', 1:5))) %>% 
   spread(product, product_id, drop = FALSE, fill = 0)
# A tibble: 3 x 6
# Groups:   id [3]
#     id product1 product2 product3 product4 product5    
#  <int>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>
#1     1      305      402      305        0        0
#2     2      200        0        0        0        0
#3     3      402      402        0        0        0

数据

df1 <- structure(list(id = c(1L, 1L, 2L, 1L, 3L, 3L), product_id = c(305L, 
 402L, 200L, 305L, 402L, 402L)), class = "data.frame", row.names = c(NA, 
 -6L))

推荐阅读