[英]rename columns in a list of dataframes
I need to be able to rename columns by name in a list of dataframes that can all expected to have the same names. 我需要能够按名称重命名所有可能具有相同名称的数据框列表中的列。
For example: 例如:
[[1]]
col1 col2
1 1 2
2 2 3
[[2]]
col1 col2
1 1 2
2 2 3
Should become: 应该成为:
[[1]]
ID col2
1 1 2
2 2 3
[[2]]
ID col2
1 1 2
2 2 3
data: 数据:
col1 <- c(1,2)
col2 <- c(2,3)
myList <- list(data.frame(col1,col2),data.frame(col1,col2))
my attempt: 我的尝试:
lapply(myList, function(x){
names(myList[[x]])[names(myList[[x]]) =="col1"] <- "ID"
})
Where did I go wrong? 我哪里做错了? I need base R. 我需要基数R。
You can use {dplyr}
and {purrr}
from the {tidyverse}
您可以使用{dplyr}
和{purrr}
从{tidyverse}
> library(purrr)
> library(dplyr)
>
> df1 <- data.frame(col1 = 1:2, col2 = 3:4)
> df2 <- data.frame(col1 = 3:2, col2 = 6:7)
>
> list(df1, df2) %>% map(~ rename(., ID = col1))
[[1]]
ID col2
1 1 3
2 2 4
[[2]]
ID col2
1 3 6
2 2 7
It also works with strings: list(df1, df2) %>% map(~ rename(., "ID" = "col1"))
它也适用于字符串: list(df1, df2) %>% map(~ rename(., "ID" = "col1"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.