Home > front end >  how to change the columns in a dataframe into lists?
how to change the columns in a dataframe into lists?

Time:02-08

I have data formatted as a dataframe.

a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- cbind(a1,a2,b1,b2,c)

I would like to change "abc" into two lists.

list <- list()
list[[1]] <- cbind(a1,a2,c)
list[[2]] <- cbind(b2,b2,c)

thanks in advance!

CodePudding user response:

Not enough details have been shared about the logic of creation of two lists but I am going to assume you want to split them based on the names. So all the columns with "a" in them are in one list and all the columns with "b" in another one. One column ("c") is constant in both the lists.

Here is a base R way using split.default -

exclude_cols <- c(5) #"c"

list_df <- lapply(split.default(abc[-exclude_cols], 
                 sub('\\d ', '', names(abc)[-exclude_cols])), function(x) {
  cbind(x, abc[exclude_cols])
})

list_df
#$a
#  a1 a2 c
#1  1  2 g
#2  2  4 h
33  3  6 i
#4  4  7 j
#5  5  8 k

#$b
#  b1 b2 c
#1  2  3 g
#2  5  1 h
#3  8  2 i
#4  1  5 j
#5  2  6 k

sub is used to remove numbers from the column name and is used as grouping variable in split.default.

sub('\\d ', '', names(abc)[-exclude_cols])
#[1] "a" "a" "b" "b"

data

a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- data.frame(a1,a2,b1,b2,c)

CodePudding user response:

If I’m understanding:

a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- data.frame(a1,a2,b1,b2,c)

my_list <- list(
    as.list(abc[, c("a1", "a2", "c")]),
    as.list(abc[, c("b1", "b2", "c")])
)
  •  Tags:  
  • Related