Home > database >  Turn a datatable into a two-dimensional list in R
Turn a datatable into a two-dimensional list in R

Time:01-13

I have a data.table (see dt). I want to turn it into a 2-dimensional list for future use (e.g. a, b and c are column names of another dt. I want to select the value of a non-missing column among a, b and c then impute into x, and so on). So the 2-dimensional list will act like a reference object for fcoalesce function.

# example
dt <- data.table(col1 = c("a", "b", "c", "d", "e", "f"),
                 col2 = c("x", "x", "x", "y", "y", "z"))

# desirable result
list.1 <- list(c("a", "b", "c"), c("d", "e"), c("f"))
list.2 <- list("x", "y", "z")

list(list.1, list.2)

Since the actual dt is much larger than the example dt, is there a more efficient way to do it?

CodePudding user response:

You can use split():

lst1 <- split(dt$col1, dt$col2)
lst2 <- as.list(names(lst1))
result <- list(unname(lst1), lst2)

result
# [[1]]
# [[1]][[1]]
# [1] "a" "b" "c"
# 
# [[1]][[2]]
# [1] "d" "e"
# 
# [[1]][[3]]
# [1] "f"
# 
# 
# [[2]]
# [[2]][[1]]
# [1] "x"
# 
# [[2]][[2]]
# [1] "y"
# 
# [[2]][[3]]
# [1] "z"
  • Related