【问题标题】:How to apply a Function on a List of Lists in R?如何在 R 中的列表列表上应用函数?
【发布时间】:2020-01-14 07:59:47
【问题描述】:

我正在尝试编写一个循环,在其中将函数应用于列表列表。 我想用 gstat 包的 idw 命令插入不同国家的温度(最高平均温度/MAXMEAN)。

idw函数需要坐标(经度、纬度)和变量MAXMEAN的信息。这些组合在数据框列表“temperatures.coordinates”(如下所示:https://imgur.com/cr3PquB)中,该列表包含 37 个国家/地区,其中每个列表再次分为 12 个月(子列表长度为 12)。 该函数还需要来自 grd.list 数据帧的信息,该数据帧是一个长度为 37 的列表,没有子列表。

应用于单个国家和单个月份,代码如下:

# Create a gridded structure

grd <- expand.grid(x = seq(from = x.range[1], to = x.range[2], by = 0.1), y = seq(from = y.range[1], to = y.range[2], by = 0.1))
coordinates(grd) <- ~x + y
gridded(grd) <- TRUE

#Interpolate surface and fix the output. Apply idw model for the data

idw <- idw(formula = MAXMEAN ~ 1, locations = temperatures.coordinates, newdata = grd)  

我试过这样做:

# Create a gridded structure
grd <- list()
for (i in 1:length(countrybounds)) {
  grd[[i]] <- expand.grid(x = seq(from = (x.range[[i]])[1], to = (x.range[[i]])[2], by = 0.1), y = seq(from = (y.range[[i]])[1], to = (y.range[[i]])[2], by = 0.1))
  coordinates(grd[[i]]) <- ~x + y
  gridded(grd[[i]]) <- TRUE
  grd.list <- grd
  gridded(grd.list[[i]]) <- TRUE 
  }

#Interpolate surface and fix the output. Apply idw model for the data

idw.list <- list()
for (i in 1:length(grd.list)) {
idw.list[[i]] <- list()
for (j in 1:length(grd[[i]])) {
idw.list[[i]][[j]] <- idw(formula = MAXMEAN ~ 1, locations = (temperatures.coordinates[[i]][[j]]), newdata = grd.list[[i]])
}
}

运行循环后我收到此错误:

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘idw’ for signature ‘"formula", "data.frame"’

这在之前的类似循环中起作用,我在其中创建温度坐标的列表:

temperatures.coordinates <- list()
for(i in 1:length(monthlymean)){
  temperatures.coordinates[[i]] <- list()
  for(j in 1:length(monthlymean[[i]])){
    temperatures.coordinates[[i]][[j]]<-(monthlymean[[i]][[j]])[,c("LON","LAT","MAXMEAN")]
  }
}

我不确定我是否提供了所有相关信息,并且我已经被困了一段时间 - 感谢任何帮助,谢谢!

【问题讨论】:

  • 如果没有数据样本,很难在代码中找到问题。如果可以,解决这种情况的最简单方法可能是将所有数据放入一个数据框中。由于这个嵌套列表似乎是按国家和年份构建的,因此应该可以创建一个包含所有数据的变量国家和年份的数据框。或者,软件包˙purrr˙ 提供了一些非常好的工具来处理列表。如果您想将函数应用于更深层次的嵌套列表,请使用purrr::map_depth()
  • 我很好奇这个对象,数据框列表“temperatures.coordinates”。数据框列表?还是列中有列表的数据框?请dput这个对象。见How to make a great R reproducible example
  • 另外,您应用于单个国家和月份的代码似乎使用了idw 中的整个对象temperatures.coordinates。您如何在该代码块中运行 single 个国家和 single 个月?
  • temperatures.coordinates 看起来像这样:imgur.com/cr3PquB。它是 37 x 12 数据帧的列表。对于 dput,我要发布整个输出吗?单一案例的代码只使用一个数据框和一个月的数据。谢谢!

标签: r loops for-loop apply gstat


【解决方案1】:

问题标题中的问题有以下答案:

a <- list(list(1,2), list(3,4))
res <- rapply(a, function(x) x^2)

按照 cmets 中的建议,您需要提供数据样本以获得代码方面的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    相关资源
    最近更新 更多