簡體   English   中英

在 R data.table [R] 中用兩列將長形改造成寬形

[英]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 等),您可以

  1. 創建一個新的分組變量,在每個代碼中的順序觀察上運行
  2. 按照這個組划分
  3. 創建一個主鍵用於合並所有結果 data.tables
  4. 最后在結果中執行鍵控合並
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM