首页 > 解决方案 > 将新值添加到 R 中的嵌套列表中

问题描述

我正在使用 Highcharts 进行可视化,Highcharter 将图表生成为类似于example_list下面的嵌套列表。我在这里总结一下,因为原始列表更长更复杂。

example_list <- list(
    x = list(
        hc_opts = list(
            series = list(
                list(group = "group_a", data = list(0,2,4,6)),
                list(group = "group_b", data = list(0,3,6,9)),
                list(group = "group_c", data = list(9,4,8,12))))))

就像 group 和 data 节点一样,我想在andtype的级别添加一个名为的元素,但仅限于 . 下的第一个和第三个元素。我基本上在寻找与以下相同的输出:groupdataseries

example_list <- list(
    x = list(
        hc_opts = list(
            series = list(
                list(group = "group_a", data = list(0,2,4,6), type = "type_X"),
                list(group = "group_b", data = list(0,3,6,9)),
                list(group = "group_c", data = list(9,4,8,12), type = "type_Y")))))

我可以使用 for 循环来做到这一点(因为我有位置和类型的向量),但应该有一种优雅的编码方式。迄今为止我最好的尝试。

locations <- c(1,3)
types <- c("type_X","type_Y")
for(i in 1:length(locations)) {
    example_list[["x"]][["hc_opts"]][["series"]][[locations[i]]][["type"]] <- types[i]
}

标签: rlist

解决方案


我们可以使用Map

example_list$x$hc_opts$series[c(1, 3)] <- Map(c, 
         example_list$x$hc_opts$series[c(1, 3)], type = types)


#$x
#$x$hc_opts
#$x$hc_opts$series
#$x$hc_opts$series[[1]]
#$x$hc_opts$series[[1]]$group
#[1] "group_a"

#$x$hc_opts$series[[1]]$data
#$x$hc_opts$series[[1]]$data[[1]]
#[1] 0

#$x$hc_opts$series[[1]]$data[[2]]
#[1] 2

#$x$hc_opts$series[[1]]$data[[3]]
#[1] 4

#$x$hc_opts$series[[1]]$data[[4]]
#[1] 6


#$x$hc_opts$series[[1]]$type
#[1] "type_X"
#...
#...

推荐阅读