从列表中获取值(冒号的右侧)

时间:2016-09-21 18:19:33

标签: r

我是R的新手,所以我确信这很简单,但我无法理解。你可以在下面看到我的对象的结构。我想循环遍历n并从冒号的右侧获取每个非空值(例如“57454470”)并对其应用函数。

> str(n)
List of 1
 $ :List of 10
  ..$ 15793766: NULL
  ..$ 15793767: chr "57454470"
  ..$ 15793769: chr "123652395"
  ..$ 15793770: chr "38098549"
  ..$ 15793771: chr "56864789"
  ..$ 15793776: chr "38722835"
  ..$ 15793779: chr "37962343"
  ..$ 15793784: chr "2100162920"
  ..$ 15793787: chr "2099439832"
  ..$ 15793791: chr "37992986"
  ..- attr(*, "dim")= int 10
  ..- attr(*, "dimnames")=List of 1
  .. ..$ rmaddrs$ReportID: chr [1:10] "15793766" "15793767" "15793769" "15793770" ...
  ..- attr(*, "call")= language by.data.frame(data = rmaddrs, INDICES = rmaddrs$ReportID, FUN = getValueFromXML)
  ..- attr(*, "class")= chr "by"

以下是dput的结果:

  dput(n[1])
    list(structure(list(`15793766` = NULL, `15793767` = "57454470", 
        `15793769` = "123652395", `15793770` = "38098549", `15793771` = "56864789", 
        `15793776` = "38722835", `15793779` = "37962343", `15793784` = "2100162920", 
        `15793787` = "2099439832", `15793791` = "37992986"), .Dim = 10L, .Dimnames = structure(list(
        `rmaddrs$ReportID` = c("15793766", "15793767", "15793769", 
        "15793770", "15793771", "15793776", "15793779", "15793784", 
        "15793787", "15793791")), .Names = "rmaddrs$ReportID"), call = by.data.frame(data = rmaddrs, 
        INDICES = rmaddrs$ReportID, FUN = getValueFromXML), class = "by"))

更新:我删除了“打印”测试,我正在尝试使用mean()进行更好的测试。

sapply(n[1], function(x) mean(x, na.rm=TRUE))

然后我不得不使用unlist和as.numeric,现在我觉得我有我需要使用自定义功能。

1 个答案:

答案 0 :(得分:1)

您使用sapply的方式会打印所有内容,但它也会返回同时打印的对象(因为它没有被分配)。要避免打印返回的对象,可以换入invisible()或分配

invisible(sapply(n[1], print))
xx = sapply(n[1], print)

(注意:此打印就像在控制台中输入1 + 1一样,生成的2将打印出来。但如果输入x = 1 + 1则无法打印。我也简化了您的{ {1}}省略匿名功能,但这与您的问题无关。)