Divs
Divs

Reputation: 137

R Change type of nested list

Updated: I have a nested list and I am trying to change the class of the deepest levels of the nested list into a data frame. I don't want the higher levels in a data frame. I also have what I tried to make as a character vector in the list under sublist 1 and C. I want C to be a character vector but it keeps showing as 'list' when I do a typeof() or class() on it. I don't want C to be converted to a data frame; instead I want to leave it as is.

Here is some example list and my attempts, updated based on the helpful comments below:

a1 <- list(  sublist1 = list(A= list(sub1= c(10, 40), sub2 = c(15, 35)), B=list(sub1 = c(100, 400), sub2 = c(150, 350)), C =c("abc","def")),
             sublist2 = list(A= list(sub1= c(3, 4), sub2 = c(5, 6)), B=list(sub1 = c(7, 8), sub2 = c(9, 11)))
             )
b_char <- as.character(c('2,3'))
typeof(b_char)

changetypefun <- function(x){
  if (is.list(x)) lapply(x, changetypefun)
  #else if (!is.list(x)) x #here I try to say if its not a list just return what it is
  #else if (names(x) == 'C') # here I try to say if its the C object, return what it is.
  #else if (typeof(x) == 'character') x #here and the statements below I try to say if it is a character or not a list, return it
  #else if (class(x) == 'character') x
  #else if (is.atomic(x)) x 
  else if (!is.list(x['C'])) x lapply(a1[['C']],paste0('as.',class(b_char)))
  else as.data.frame(x)
}
result <- changetypefun(a1)

Thank you so much for your help.

Upvotes: 2

Views: 456

Answers (2)

dcsuka
dcsuka

Reputation: 2997

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:

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

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


changetypefun(a1)

Upvotes: 2

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

With the rrapply package:

library(rrapply)

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

Upvotes: 1

Related Questions