更新: 我有一个嵌套列表,我试图将嵌套列表最深级别的类更改为数据框。我不想要数据框中的更高级别。我还在子列表 1 和 C 下的列表中尝试将其作为字符向量。我希望 C 成为字符向量,但当我对其执行 typeof() 或 class() 时,它一直显示为“列表” 。我不想将C转换为数据框;相反,我想保持原样。
这是一些示例列表和我的尝试,根据以下有用的评论进行更新:
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)
非常感谢您的帮助。
最佳答案
对上一个问题的答案进行简单修改即可达到目的。只需将 else x
子句更改为 else as.data.frame(x)
即可:
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)
关于R 更改嵌套列表的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73423600/