1

These questions:

Changing Column Names in a List of Data Frames in R

Changing names in a list of dataframes

Both have great solutions to changing column names, but the only column name I want to change is the first column. The data frames in my list only have the first column in common.

Here is a reproducible example of the issue that I'm having:

df1 <- data.frame(A = 1:5, B = 1:5)
df2 <- data.frame(A = 11:15, B = 21:25)
ldf <- list(df1, df2)
ldf <- lapply(ldf, setNames, "State")
L
[[1]]
  State NA
1     1  1
2     2  2
3     3  3
4     4  4
5     5  5

[[2]]
  State NA
1    11 21
2    12 22
3    13 23
4    14 24
5    15 25

How do I specify a single column in lapply and leave the rest alone?

RAFrancais
  • 57
  • 4

2 Answers2

3

We can use lapply like :

lapply(ldf, function(x) {names(x)[1] <- "State";x})

#[[1]]
#  State B
#1     1 1
#2     2 2
#3     3 3
#4     4 4
#5     5 5

#[[2]]
#  State  B
#1    11 21
#2    12 22
#3    13 23
#4    14 24
#5    15 25
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Perfect, I really need to learn functions. I tried using ldf <- lapply(ldf, names[1], "State"), which didn't work for obvious reasons. I will accept this answer when the timer allows me to. – RAFrancais Dec 25 '19 at 06:31
2

We can use rename_at

library(purrr)
library(dplyr)
map(ldf, ~ .x %>%
              rename_at(1, ~ "State"))
#[[1]]
#  State B
#1     1 1
#2     2 2
#3     3 3
#4     4 4
#5     5 5

#[[2]]
#  State  B
#1    11 21
#2    12 22
#3    13 23
#4    14 24
#5    15 25

Or with select

map(ldf, ~ .x %>%
             select(State = 1, everything()))

Or using setnames from data.table

library(data.table)
lapply(ldf, setnames, old = 1, new = 'State')
ldf
#[[1]]
#  State B
#1     1 1
#2     2 2
#3     3 3
#4     4 4
#5     5 5

#[[2]]
#  State  B
#1    11 21
#2    12 22
#3    13 23
#4    14 24
#5    15 25

Or using base R

lapply(ldf, setNames, c("State", names(ldf[[1]][-1])))
akrun
  • 874,273
  • 37
  • 540
  • 662