r - 定义列中的展开()
问题描述
基本上,对于每个 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
解决方案
我们可以通过 'id' 创建一个序列列,然后spread
. 请注意,简单spread
的 ing 直到 5 才会包含所有“产品”,因为数据中缺少这些。为了做到这一点,将序列创建为factor
从levels
“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))
推荐阅读
- openwrt - 文件名和路径太长导致为 netgear r7800 编译 openwrt-trojan 错误
- python - PyQt5:样式表和来自 QWidget 的继承
- python - 使用 Selenium 和 Python 获取特定元素值
- javascript - 新用户注册后将用户写入 Firestore
- ssh - 具有 ssh 隧道自动化的交互式作业
- python - Python:如何读取多个 .NBT 文件并导出为 JSON?
- angular - Angular 项目返回类型的 esLint 规则
- autodesk-forge - 通过 API 将 Revit 模型文件上传到 BIM360 并保持链接
- javascript - 在行内最近的第三个 div 之后添加创建的元素
- docker - 无法从内部的 Docker 容器和 WSL2 实例连接 Xdebug