r - 将新值添加到 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
的级别添加一个名为的元素,但仅限于 . 下的第一个和第三个元素。我基本上在寻找与以下相同的输出:group
data
series
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]
}
解决方案
我们可以使用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"
#...
#...
推荐阅读
- r - Shiny to Markdown PDF 在第二次和后续运行中失败
- javascript - 如何仅使注销按钮出现而没有来自单独组件的CSS
- r - R数据框,用来自同一变量的值更改变量中的值
- ruby-on-rails - Heroku staging 应用程序是否与评论应用程序共享数据库?
- javascript - Javascript D3位置工具提示到图表
- android - IllegalStateException:使用 BottomNavigation 时尚未附加 Fragment
- sql-server - 获取最接近 AVG TSQL 函数的值
- qt - 如果它是使用 QRegExp 的逗号,如何删除第一个字符?
- android - 如何有选择地使用 Google Play 服务包?
- unit-testing - 如何定义模拟方法被调用零次