Search code examples
rdata.tablereshapedcast

Long to Wide Multiple variables in R


while converting Long data to wide How do I provide multiple columns to timevar argumnet in reshape

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

like example 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

but I need output like below:

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

order of elements in n1, n2, n3 columns of output doesn't matter. only unique elements from n1 and n2 cols is required. Also I have have multiples columns like n1, n2, n3,,, n in my actual DT


Solution

  • Here is a rough concept that seems to achieve the desired result.

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