长到宽R中的多个变量

问题描述 投票:2回答:1

将Long数据转换为wide时如何在reshape中为timevar参数提供多个列

`reshape(DT, idvar="Cell", timevar = "n1", direction="wide")`

比如timevar=c("n1","n2"....)

DT<-data.table(Cell = c("A","A","B","B"), n1=c("x","y","y","a"), n2=c("t","x","x","z"))

   Cell n1 n2
1:    A  x  t
2:    A  y  x
3:    B  y  x
4:    B  a  z

但我需要输出如下:

Cell  n1    n2  n3  n4
A      x    y   t   NA
B      x    y   a   z

输出的n1,n2,n3列中的元素顺序无关紧要。只需要来自n1和n2 cols的唯一元素。在我的实际DT中,我有多个列,如n1,n2,n3 ,,, n

r data.table reshape dcast
1个回答
2
投票

这是一个粗略的概念,似乎达到了预期的效果。

foo <- function(x, y, n) {
  l <- as.list(unique(c(x, y)))
  if (length(l) < n) l[(length(l)+1):n] <- NA_character_
  l
}


DT[, foo(n1, n2, 4), Cell]

#    Cell V1 V2 V3   V4
# 1:    A  x  y  t <NA>
# 2:    B  y  a  x    z

# Set the names by reference
setnames(DTw, c("Cell", paste0("n", 1:4)))
© www.soinside.com 2019 - 2024. All rights reserved.