1

I have the following tables:

df <- data.frame(DATE = c('07/01/2022', '08/01/2022'),
                 `0` = c(4, 4),
                 `1` = c(5, 3),
                  `2` = c(5,3), check.names = FALSE)
Date 0 1 2
07/01/2022 4 5 5
08/01/2022 4 3 3
df2 <- data.frame(V1 = 2,
                 V2 = 4,
                 V3 = 5)
V1 V2 V3
2 4 5

I'm trying to add the values of V1, V2, and V3 below the last row of the first table, but only for columns 0:3. The output should look like this:

Date 0 1 1
07/01/2022 4 5 5
08/01/2022 4 3 3
2 4 5

I tried rbind and bind_rows, but neither worked.

nwk123
  • 35
  • 7
  • Please use `dput()` to share reproducible examples. Also what did you try? Did you try `rbind()` for example? – Sotos Jun 06 '23 at 14:23
  • Fixed that. I tried rbind and bind_rows – nwk123 Jun 06 '23 at 14:34
  • Change the column names on df2 to match df1 then see solutions at https://stackoverflow.com/questions/18003717/efficient-way-to-rbind-data-frames-with-different-columns – zx8754 Jun 06 '23 at 15:10

2 Answers2

1

Using rbind, you can do,

rbind(df, 
      setNames(data.frame(DATE = '', df2), 
               names(df))
     )

        DATE X0 X1 X2
1 07/01/2022  4  5  5
2 08/01/2022  4  3  3
3             2  4  5
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • Convert to data.table, then we can just do: `rbind(DT1, DT2, fill = TRUE)` – zx8754 Jun 06 '23 at 15:11
  • How would I save this to the original datatable, so I could modify it further? For example, I tried manipulated_data[3:15] <- rbind(manipulated_data[3:15], setNames(data.frame(TOTAL = 'Weights', manipulated_data_numbers), names(manipulated_data[3:15]))) but that didn't work – nwk123 Jun 06 '23 at 15:55
0

An approach using rbindlist from data.table

library(data.table)

rbindlist(list(df1, cbind(Date = "", df2)), use.names=F)
         Date 0 1 2
1: 07/01/2022 4 5 5
2: 08/01/2022 4 3 3
3:            2 4 5
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29