0

I have 20 different dataframes that have two equal columns (year, rn) but one column is named slightly different in each DF (pci1995$complexity_index_product, pci1995$complexity_index_product etc.).

I want a dataframe with three columns that merges basically all dataframes below each other (rn, year, pci) When I try:

pci_allyears<-bind_rows(pci_df1995,
  pci_df1996,
  pci_df1997,
  pci_df1998,)

I get one year and on rn column with all the values, but unfortunately each pci column is still shown as separate column because they are of course not identical (differ by year). How can I fix this to have only three columns?

Taufi
  • 1,433
  • 6
  • 12
  • Could you post a sample of maybe two of the dataframes using `dput(head(pci_df1997))` and `dput(head(pci_df1998))`? `dplyr::bind_rows` should work here. – LMc Feb 03 '21 at 16:13

1 Answers1

0

Give all your data the same column names. First, get all your data frames in a list. I assume they have the same naming convention pci_df**** where the * are numbers, and that it is the 3rd column that has the variable name.

pci_df = mget(ls(pattern = "pci_df[0-9]{4}"))
pci_df = lapply(pci_df, setNames, c("year", "rn", "complexity_index"))
pci_df = bind_rows(pci_df)

I'd recommend reading my answer at the How to make a list of data frames FAQ for a bit more context and related advice.

Gregor Thomas
  • 104,719
  • 16
  • 140
  • 257
  • thank you very much for this swift answer which really saved my day! Following up on this: I have similar information that is first stored in a list for each year and that then needs to be turned into a dataframe before I can use the command you provided above. Ihave tried mget(ls(pattern) to grap the lists but it somehow does not work: – fabian_alex Feb 03 '21 at 17:12
  • the command is: eci_df1995%mutate(year="1995") eci_df1996%mutate(year="1996") then i use eci_df=mget . but what can i do not having to copy-paste the command for each year? – fabian_alex Feb 03 '21 at 17:13
  • Please post a reproducible example in another question. I can't tell what's going on down here. If `mget(ls(pattern = ...))` doesn't work, then the pattern you're using must not be matching the names. – Gregor Thomas Feb 03 '21 at 18:11