首页 > 解决方案 > 迭代地为R中列表中的列表上完成的计算分配变量名称?

问题描述

我在 R studio 中遇到问题已有一段时间了,我想先声明一下,我对 R 还是很陌生,仍然不知道所有“最快”的做事方法,但任何帮助和耐心都会很棒.

我是一名研究人员,必须计算不同气象站的气象模型的技能分数,并且有数千个数据点要迭代,我认为最简单的方法是在文件中读取并将每个文件作为单独的列表存储在列表中.

完成此操作后,我将遍历列表中的每个列表,并计算不同的错误分数(正常错误、RMSE 等),从而使我不必复制和粘贴大约 121 个不同的循环。这种做事的方法显然是A)不是一个好方法,或者B)我没有牢牢把握做这件事的最佳方法。

所以,下面是一个简单的例子:

# The weather model forecasts
model1 <- c(1:15)
model2 <- c(1:15)
model3 <- c(1:15)

# What actually happened (verification/measured values)
verification_model1 <- c(1:15)
verification_model2 <- c(1:15)
verification_model3 <- c(1:15)

# List of lists containging total model data
totalmodeldata <- list(model1,model2,model3)
totalverificationdata <-list(verification_model1,verification_model2,verification_model3)

# Calculate normal error
for (val in totalmodeldata){
  for (ob in totalverificationdata){
    uniquevarname <- val - ob # here is the issue!
  }
}

所以这是我的一个问题,使它成为一个简单的问答......

  1. 是否有一种简单的方法可以在列表计算中为这些单独的列表分配唯一的变量名称?因为就目前而言,代码执行了它应该对错误计算做的事情,但只存储了它计算的最后一个列表(model3.

理想情况下,它会做一些计算model1 VS的正常误差的事情。verify_model1 将数据分配给一个变量,然后移动到第二个列表,依此类推,因此我对模型 1、模型 2 和模型 3 有正常错误。

更新:好的,我们正在到达某个地方。这是我想要的输出......在将模型数据(model1..2..3 等)和验证数据(verifcation_model1..2..3 等)声明到“总”列表中后,a for 循环或类似函数将循环遍历并对每个模型和验证数据列表进行以下减法:

unqiue_var_error1 <- model1 - verification_model1
unqiue_var_error2 <- model2 - verification_model2
unqiue_var_error3 <- model3 - verification_model3

输出/存储的数据看起来像每个模型的简单数据向量......这是我工作中正常错误的实际输出:

> head(model1,n = 15L)
 [1] -6  0  1  0 -4 -2  2  0 -3 -2 -3 -5 -5 -5 -5

这样,一旦该循环完成,每个模型都会出现正常错误。

标签: rloopsfor-loopnested-lists

解决方案


这是使用嵌套的解决方案purrr::map2
(您实际上并不需要嵌套映射,它只允许将结果包装在单个数据框中。)

library(tidyverse)

map2_df(totalmodeldata, totalverificationdata,
     function(model, verify) {
       map2_dbl(model, verify, ~.x - .y)
     }
)

# A tibble: 10 x 3
   model1 model2 model3
    <dbl>  <dbl>  <dbl>
 1 -1.22  -0.611 -1.50 
 2  1.82   0.911  1.71 
 3  3.06   1.53   3.84 
 4 -1.40  -0.700 -1.37 
 5 -1.33  -0.665 -1.27 
 6  1.57   0.787  2.43 
 7  0.252  0.126  0.482
 8  1.77   0.886  1.14 
 9 -0.200 -0.100 -0.543
10  0.642  0.321  0.419

数据:

# added randomness to avoid having all zeros show up in diff scores

# The weather model forecasts
set.seed(123)
n <- 10
model1 <- rnorm(n)
model2 <- model1 * .5
model3 <- model1 * 1.5

# What actually happened (verification/measured values)
set.seed(234)
verification_model1 <- rnorm(n)
verification_model2 <- verification_model1 * .5
verification_model3 <- verification_model1 * 1.5

# List of lists containging total model data
totalmodeldata <- 
  list(model1, model2, model3) %>% set_names('model1', 'model2', 'model3')

totalverificationdata <-
  list(verification_model1, verification_model2, verification_model1) %>% 
  set_names('ver_model1', 'ver_model2', 'ver_model3')

注意:该purrr包是对基本 R 系列功能的一个 tidyverse apply(根据 OP 注释,它与 R >= 3.2 兼容)。


推荐阅读