[英]Reshape long to wide with two columns to expand in R data.table [R]
我正在尝试使用两个字符串列转换以下数据以从长扩展为宽。 R 中实现以下最有效的方法是什么:
样本数据:
data_sample <- data.frame(code=c(1,1,2,3,4,2,4,3),name=c("bill","bob","rob","max","mitch","john","bart","joe"),numberdata=c(100,400,300,-200,300,-500,100,-400))
期望 function 产生以下数据集:
data_desired <- data.frame(code=c(1,2,3,4),name1=c("bill","rob","max","mitch"),name2=c("bob","john","joe","bart"),numberdata1=c(100,300,-200,300),numberdata2=c(400,-500,-400,100))
我正在使用大数据(真实代码为 1-100,000),是否有有效的 data.table 方法来完成此操作? 谢谢!
您可以使用dcast
-
library(data.table)
setDT(data_sample)
dcast(data_sample, code~rowid(code), value.var = c('name', 'numberdata'))
# code name_1 name_2 numberdata_1 numberdata_2
#1: 1 bill bob 100 400
#2: 2 rob john 300 -500
#3: 3 max joe -200 -400
#4: 4 mitch bart 300 100
如果命名无关紧要(例如 name1、name2 等),您可以
data_sample <- data.frame(code=c(1,1,2,3,4,2,4,3),name=c("bill","bob","rob","max","mitch","john","bart","joe"),numberdata=c(100,400,300,-200,300,-500,100,-400))
setDT(data_sample)
# Create new group indicating the variable "*group*"
data_sample[, `*group*` := seq.int(.N), by = code]
# Split the data.table according to the new group
groups <- split(data_sample, by = '*group*')
# Set key on each group to the "code" variable
lapply(groups, \(dt){
setkey(dt, code)
# Remove group
dt[, `*group*` := NULL]
})
# Merge the result (using Reduce here
res <- Reduce(\(dt1, dt2)merge(dt1, dt2, all = TRUE), groups)
# Reorder columns
setcolorder(res, sort(names(res)))
res
code name.x name.y numberdata.x numberdata.y
1: 1 bill bob 100 400
2: 2 rob john 300 -500
3: 3 max joe -200 -400
4: 4 mitch bart 300 100
这样做的好处当然是,这适用于每个代码有 2 个以上条目的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.