繁体   English   中英

如何在R列表中应用函数?

[英]How to apply a Function on a List of Lists in R?

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

idw函数需要坐标(经度,纬度)和变量MAXMEAN的信息。 这些组合在数据框列表“temperature.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")]
  }
}

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

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

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

正如评论中所建议的那样,您需要提供数据样本以获取有关代码的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM