Alex808
Alex808

Reputation: 101

How to create data.table with different size of columns

I create data.table like this.

DT = data.table(A=c(1,2,3), B=c(1,2,3,4,5))

But I get this result.

   A B
1: 1 1
2: 2 2
3: 3 3
4: 1 4
5: 2 5

but I'd like to get this.

   A B
1: 1 1
2: 2 2
3: 3 3
4: NA 4
5: NA 5

How can I create data.table with different size?

Upvotes: 6

Views: 2754

Answers (4)

MichaelChirico
MichaelChirico

Reputation: 34763

Not very extensible, but this works as well:

data.table(A = 1:3)[ , I := .I][data.table(B = 1:5)[ , I := .I], on = "I"]

#     A I B
# 1:  1 1 1
# 2:  2 2 2
# 3:  3 3 3
# 4: NA 4 4
# 5: NA 5 5

(append [ , I := NULL] to remove the added column)

Upvotes: 0

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

install.packages("qpcR")
library(qpcR)

df <- data.table(qpcR:::cbind.na(A=c(1,2,3), B=c(1,2,3,4,5)))
  A B
1  1 1
2  2 2
3  3 3
4 NA 4
5 NA 5

Upvotes: 2

Choubi
Choubi

Reputation: 680

I've just created a wrapper that, instead of recycling elements, adds NA values at the end of each vector so that the length of all input vectors are the same:

data.table2 <- function(...) {

  args <- list(...)
  max_length <- max(sapply(args, length))
  foo <- function(x) {
    y <- rep(NA, max_length - length(x))
    return(c(x, y))
  }
  new_args <- lapply(args, foo)
  do.call(data.table, new_args)

}

data.table2(A=c(1,2,3), B=c(1,2,3,4,5))

> DT
    A B
1:  1 1
2:  2 2
3:  3 3
4: NA 4
5: NA 5

Upvotes: 1

akrun
akrun

Reputation: 887971

We keep the vector of unequal length in a list ('lst'), then loop through the list elements, append NA at the end and convert to data.table.

lst <- list(A=c(1,2,3), B=c(1,2,3,4,5))
DT <- setDT(lapply(lst, `length<-`, max(lengths(lst))))[]
DT
#    A B
#1:  1 1
#2:  2 2
#3:  3 3
#4: NA 4
#5: NA 5

Upvotes: 7

Related Questions