1

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.

OTStats
  • 1,820
  • 1
  • 13
  • 22
  • 1
    https://stackoverflow.com/questions/19297475/simplest-way-to-get-rbind-to-ignore-column-names – cicero Jun 25 '19 at 14:09
  • 2
    If you put them in a list you can `lapply` to change the names, but if you are just trying to `rbind` them you can use `data.table::rbindlist(list(df, df2), use.names = F)` – IceCreamToucan Jun 25 '19 at 14:09

2 Answers2

1

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)
DSGym
  • 2,807
  • 1
  • 6
  • 18
  • for example, if the name of every data frame is produk1, produk2,... produk 5, then i have to do rbind like this "rbindlist(produk1,produk2,produk3,produk4,produk5, use.names = F)"? – Nicodemus Sigit Sutanto Jun 25 '19 at 14:27
  • you could also do this: ```dplyr::bind_rows(lapply(dflist, setNames, nm = c("prod", "code", "tot")))```. This would rename and then rbind all rows. However, data.table is the better solution. If the answer was helpful, please do not forgot to accept it :-) – DSGym Jun 25 '19 at 14:29
  • 1
    rbindlist rbinds a list. So you have to write it like this: ```rbindlist(list(produk1,produk2,produk3,produk4,produk5), use.names = F)```. Do not forget the list function. – DSGym Jun 25 '19 at 14:31
0

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
cbo
  • 1,664
  • 1
  • 12
  • 27