R中的从长到宽多个变量

时间:2018-10-09 09:40:16

标签: r data.table reshape dcast

将长数据转换为宽数据时,如何以整形方式向timevar argumnet提供多列

`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列中的唯一元素。我实际的DT中也有n1,n2,n3,...,n等多个列

1 个答案:

答案 0 :(得分: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)))