【问题标题】:Long to Wide Multiple variables in RR中的长到宽多个变量
【发布时间】:2019-03-14 01:05:19
【问题描述】:

在将长数据转换为宽数据时如何在 reshape 中向 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 cols 中的唯一元素。我的实际 DT 中有多个列,例如 n1、n2、n3、、、n

【问题讨论】:

  • 我的问题是关于如何在 timevar 参数中分配多列
  • 就像我说的顺序对我来说并不重要.. 只有列 n1 和 n2 中的唯一元素才能用于 B

标签: r data.table reshape dcast


【解决方案1】:

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

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)))

【讨论】:

  • 这对我来说看起来像是开箱即用的解决方案。像我说的另一个问题,我的 n1,n2 列更像是直到 n8 如何将其纳入您的解决方案
  • 只需将 foo 的最后一个参数增加到8
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多