用`ends_with`映射列表以应用自定义错误函数

问题描述 投票:0回答:1

我有一个看起来像这样的列表:

enter image description here

我正在尝试将其置于map并使用mutate功能来应用自定义功能。该列表称为results,我想计算preds与数据帧中另一列之间的误差。在所有列表中,该列的共同主题是其中一列的最后的1

如何使用containends_with或类似方法计算自定义函数? preds列在所有数据帧中均相同。

rse <- function(x, y){
  sqrt((x - y)**2)      
}

x <- map(results, ~mutate(
  error = rse(ends_with("1"), preds)
))

数据:

list(`c(5, 19)` = structure(list(date = structure(c(16801, 16802, 
16803, 16804, 16805, 16806), class = "Date"), year = c(2016, 
2016, 2016, 2016, 2016, 2016), c_farolillo = c(17, 9, 8, 3, 4, 
4), plaza_eliptica = c(25, 29, 18, 11, 13, 9), c_farolillo1 = c(17, 
9, 8, 3, 4, 4), preds = c(7.08282661437988, 9.66606140136719, 
5.95918273925781, 3.81649804115295, 4.26900291442871, 3.38829565048218
)), row.names = c(NA, 6L), class = "data.frame"), `c(7, 1, 2, 18)` = structure(list(
    date = structure(c(16801, 16802, 16803, 16804, 16805, 16806
    ), class = "Date"), year = c(2016, 2016, 2016, 2016, 2016, 
    2016), pza_del_carmen = c(12, 10, 10, 6, 8, 4), pza_de_espana = c(28, 
    21, 14, 8, 10, 6), escuelas_aguirre = c(17, 24, 19, 20, 22, 
    16), retiro = c(6, 5, 7, 3, 2, 2), pza_del_carmen1 = c(12, 
    10, 10, 6, 8, 4), preds = c(15.3020477294922, 16.007848739624, 
    15.3953952789307, 9.59985256195068, 9.85349082946777, 8.42792892456055
    )), row.names = c(NA, 6L), class = "data.frame"))
r
1个回答
0
投票

我们用list遍历data.framesmap(“结果”),然后使用mutate_at通过指定ends_with功能的同时应用rse“ 1”的名称来修改列'y'为'preds'栏

library(dplyr)
library(purrr)
results <- map(results, ~ .x %>%
                 mutate_at(vars(ends_with("1")), list(new = ~ rse(., y = preds))))
© www.soinside.com 2019 - 2024. All rights reserved.