【问题标题】:Replace NULL is list with NA用 NA 替换 NULL 是列表
【发布时间】:2020-07-01 20:17:00
【问题描述】:

我正在尝试从列表中提取元素,将 NULL 替换为 NA。我的简单 ifelse 和 is.null 语句似乎将子列表截断为第一个元素。怎么回事?

Henry_VIII.list <- list(name="Henry Tudor",DOB=as.Date("28 June 1491", format=("%d %B %Y")),place_of_birth="Palace of Placentia, Greenwich, Kent",
                        DOD=as.Date("28 January 1547", format=("%d %B %Y")),place_of_death="Palace of Whitehall, London")

Catherine_of_Aragon.list <- list(name="Catherine of Aragon",DOB=as.Date("16 December 1485", format=("%d %B %Y")),place_of_birth="Archiepiscopal Palace of Alcalá de Henares, Alcalá de Henares, Castile", DOD=as.Date("7 January 1536", format=("%d %B %Y")),place_of_death="Kimbolton Castle, England")
Anne_Boleyn.list <- list(name="Anne Boleyn", DOB="?? July 1501", place_of_birth="Blickling Hall, Norfolk or Hever Castle, Kent", DOD=as.Date("19 May 1536", format=("%d %B %Y")),place_of_death="Tower of London, London")

Henry_VIII.list$spouse <- list(Catherine_of_Aragon.list,Anne_Boleyn.list)
Emily_Dickinson.list <- list(name="Emily Dickinson",DOB=as.Date("10 December 1830", format=("%d %B %Y")),place_of_birth="Amherst, Massachusetts, US",
                             DOD=as.Date("15 May 1886", format=("%d %B %Y")),place_of_death="Amherst, Massachusetts, US")

biography.list <- list(Henry_VIII.list,Emily_Dickinson.list)
sapply(1:2, function(x) biography.list[[x]]$spouse) ## gets correct results
sapply(1:2, function(x) ifelse(is.null(biography.list[[x]]), NA, biography.list[[x]])) ## kills Anne Boleyn

【问题讨论】:

    标签: r list sapply


    【解决方案1】:

    我们也可以做作业

    biography.list <- lapply(biography.list, function(x) 
              {x$spouse[is.null(x$spouse)] <- NA;x})
    

    【讨论】:

      【解决方案2】:

      我认为您不想使用ifelse,而是应该使用 if 语句。 ifelse 想要返回一个向量,而不是一个列表。听起来您希望返回一个列表。

      sapply(1:2, 
             function(x){
                 if(is.null(biography.list[[x]]$spouse)){
                     NA
                 }else{
                     biography.list[[x]]$spouse
                 }
             })
      

      【讨论】:

      • 谢谢!我没有意识到 ifelse 和 if else 给出了如此不同的结果!我应该假设 ifelse 强制转换为向量吗?
      • 我相信是的。在ifelse的帮助文件中,它的Value是一个向量
      猜你喜欢
      • 2021-10-22
      • 2017-09-13
      • 2019-05-20
      • 1970-01-01
      • 2019-07-22
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      相关资源
      最近更新 更多