Home > other >  Copy one column into existing columns and keep name of existing columns
Copy one column into existing columns and keep name of existing columns

Time:04-07

I have the following data:


 structure(list(Name = c("A", "B", "C", "D"), `Data 2018-08` = c(4L, 
5L, 2L, 4L), `Data 2018-09` = c(5L, 4L, 5L, 4L), `Data 2018-10` = c(9L, 
4L, 4L, 2L), `Data 2018-11` = c(7L, 3L, 6L, 7L), `Data 2018-12` = 9:6, 
    `Data 2019-01` = c(5L, 9L, 7L, 2L), `Data 2019-02` = c(9L, 
    6L, 3L, 4L), `Data 2019-03` = c(8L, 7L, 4L, 6L), `Data 2019-04` = c(7L, 
    6L, 6L, 5L), `Data 2019-05` = c(6L, 8L, 7L, 7L), `Data 2019-06` = c(3L, 
    7L, 2L, 7L), `Data 2019-07` = c(5L, 8L, 7L, 2L), `Data 2019-08` = c(5L, 
    7L, 3L, 3L), `Data 2019-09` = c(7L, 4L, 5L, 4L), `Data 2019-10` = c(5L, 
    2L, 8L, 2L)), class = "data.frame", row.names = c(NA, -4L
))

How can I copy the values in column 09-2019 to all columns from 08-2018-08-2019 and keeping the columns' original name?

When I use mutate from the dplyr package, new columns are added instead of replacing the old values of the already existing columns.

CodePudding user response:

If I understand what you are asking, and you want to use mutate, this should work:

library(dplyr)
df  %>% 
    mutate(across(`Data 2018-08`:`Data 2019-08`, ~ `Data 2019-09`))

Edit: changed to tidy evaluation using ~.

  • Related