r - Map conditionally over list of dataframes in R
问题描述
I have a list of similar dataframes--some have the correct column, some have the incorrect column, and some have both. I am have a lot of tables so am looking for a solution that loops through them without if statements or case_when. Maybe something using purrr::map_at
or purrr::map_if
??
Here's a simplified example, where I want to rename "rowid_2" to "rowid" for all dfs.
library(tidyverse)
mtcars1 <- mtcars %>% rowid_to_column(var = "rowid_2")
mtcars2 <- mtcars1 %>% mutate(rowid = rowid_2)
dfs <- list(mtcars1, mtcars2)
dfs %>% map(names)
#> [[1]]
#> [1] "rowid_2" "mpg" "cyl" "disp" "hp" "drat" "wt"
#> [8] "qsec" "vs" "am" "gear" "carb"
#>
#> [[2]]
#> [1] "rowid_2" "mpg" "cyl" "disp" "hp" "drat" "wt"
#> [8] "qsec" "vs" "am" "gear" "carb" "rowid"
Here is my desired output:
list(
mtcars1 %>% rename(rowid = rowid_2),
mtcars2 # rowid_2 could also be deselected
) %>% map(names)
#> [[1]]
#> [1] "rowid" "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs"
#> [10] "am" "gear" "carb"
#>
#> [[2]]
#> [1] "rowid_2" "mpg" "cyl" "disp" "hp" "drat" "wt"
#> [8] "qsec" "vs" "am" "gear" "carb" "rowid"
I tried this, but then I have two "rowid" columns in mtcars2
.
dfs %>% map(~.x %>% rename_with(~"rowid", matches("rowid_2"))) %>% map(names)
#> Error: Names must be unique.
#> x These names are duplicated:
#> * "rowid" at locations 1 and 13.
解决方案
You can use map_if
to only do the rename if rowid_2
exists in names(x)
and rowid
does not.
dfs %>% map_if(function(x) "rowid_2" %in% names(x) & !"rowid" %in% names(x),
function(x) rename(x, rowid = rowid_2)) %>%
map(names)
推荐阅读
- r - 浮动外部的 r markdown 标题中的图形标题错误
- assembly - 返回地址寄存器如何在不将返回地址存储在堆栈上的处理器体系结构中工作?
- c# - 获取 Windows 资源管理器中显示的文件/目录所有者
- c++ - 成员“Renderer::backgroundTex”不是类型名称
- oracle11g - sql 命令行中的 sql not a valid month 错误
- nginx - Nginx 在 proxy_pass 中接受斜杠或没有斜杠
- typedef - 系统 Verilog 条件类型定义
- json - 用于从文件中读取键值并转换为 JSON 的 Shell 脚本
- c - 未使用的输出参数
- node.js - 迭代 node.js 进程事件时没有重载匹配此调用