Home > Back-end >  R Change type of nested list
R Change type of nested list

Time:08-20

I have a nested list and I am trying to change the class of the deepest levels of the nested list (labeled 'A' and 'B') into a data frame. I don't want the higher levels in a data frame.

Here is some example list:

a1 <- list(  sublist1 = list(A= list(sub1= c(10, 40), sub2 = c(15, 35)), B=list(sub1 = c(100, 400), sub2 = c(150, 350))),
             sublist2 = list(A= list(sub1= c(3, 4), sub2 = c(5, 6)), B=list(sub1 = c(7, 8), sub2 = c(9, 11))))

class(a1) #list

b <- as.data.frame(c(2,3))
class(b) #data.frame

I tried this which made sub1 and sub2 data frames from sublist1 and removes the A and B names.

for(i in 1:2){
  for(j in 1:2){
a2<- lapply(a1[[i]][[j]],paste0('as.',class(b)))
return(a2)
  }
}

I tried my first attempt at writing a recursive function as well, but sadly this also did not work. It doesn't differentiate between the levels, as in there is no direction to only make A and B levels into data frames, but there is probably some other issue in it as well. The reason I wanted to use a recursive function is that my actual data is a much larger list of lists that I want to implement this type of code on.

changetypefun <- function(xnew){
  classx <- class(xnew) == class(b)
  if(any(classx == FALSE)) class(xnew)[classx] <- class(b)
  if (is.list(xnew)) lapply(xnew, changetypefun)
  else xnew
}
result <- changetypefun(a1)

Thank you so much for your help.

CodePudding user response:

A simple modification of the answer to your previous question does the trick here. Just change the else x clause to else as.data.frame(x) as so:

changefun <- function(x){
  if (is.list(x)) lapply(x, changefun)
  else as.data.frame(x)
}

changefun(a1)

CodePudding user response:

With the rrapply package:

library(rrapply)

rrapply(
  a1, 
  condition = is.atomic,
  f = as.data.frame
)
  • Related