how to change column name in several data frame in the same time?

I have five data frames which have same number of columns. I want to use rbind to append my data, but they have different variable names. Fortunately, it has same form like this.

date prod1 code1 tot1

date prod2 code2 tot2

...

date prod5 code5 tot5

I want to delete the number-code at the same time, so then I can rbind my data frames. How can I do this?
Thanks in advance.

Upvotes: 1

Views: 387

Answers (2)

DSGym
DSGym

Reputation: 2867

Since the questions was how to change the column names, I will address this problem first:

lapply(dflist, setNames, nm = new_col_name)

df1 <- data.frame(prod1 = 1:5, code1 = 1:5, tot1 = 1:5)
df2 <- data.frame(prod2 = 1:5, code2 = 1:5, tot2 = 1:5)

dflist <- list(df1, df2)

lapply(dflist, setNames, nm = c("prod", "code", "tot"))

[[1]]
   prod code tot
1     1    1   1
2     2    2   2
3     3    3   3
4     4    4   4
5     5    5   5


[[2]]
   prod code tot
1     1    1   1
2     2    2   2
3     3    3   3
4     4    4   4
5     5    5   5

As already mentioned it may be better just to ignore column names and use rbindlist from data.table to bind rows.

data.table::rbindlist(dflist, use.names = F)

Upvotes: 1

cbo
cbo

Reputation: 1763

You can do it using magrittr and dplyr :

d1 <- mtcars
d2 <- d1
d3 <- d1

names(d2) <- paste0(names(d2), "_2")
names(d3) <- paste0(names(d2), "_3")

rbind(d1, d2, d3) # gives an error, ok
#> Error in match.names(clabs, names(xi)): les noms ne correspondent pas aux noms précédents

library(magrittr, quietly = TRUE, warn.conflicts = FALSE)
library(dplyr, quietly = TRUE, warn.conflicts = FALSE)

df_list <- list(d2, d3)
df_list <- lapply(df_list, magrittr::set_colnames, names(d1))

df_final <- rbind(d1, dplyr::bind_rows(df_list) )
nrow(df_final) == 3* nrow(d1)
#> [1] TRUE

Upvotes: 0

Related Questions