Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add variables, make the it as equally dataframe

There is dataframe raw_data_2 , I want to add variables e_2022 b_2023,the result as dataframe raw_data_2_fixed .How to add them by easy code ? (In actual, i have to add so many variables, type in one by one will NOT be good choice).

library(tidyverse)
raw_data_2 <- data.frame(category=c('A','B','C'),
                         
                       a_2022=c(1,2,3),
                       b_2022=c(0.1,0.4,0.3),
                       
                       a_2023=c(1.5,3,4),
                       e_2023=c(0.3,0.7,0.5)
                       
                       )

The wished dataframe as below (added variable e_2022 b_2023)

raw_data_2_fixed <- data.frame(category=c('A','B','C'),
                               
                               a_2022=c(1,2,3),
                               b_2022=c(0.1,0.4,0.3),
                               **e_2022=c(NA,NA,NA),**
                               
                               a_2023=c(1.5,3,4),
                               *b_2023=c(NA,NA,NA),*
                               e_2023=c(0.3,0.7,0.5)
                               )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can pivot, separate, complete and pivot back:

library(tidyr)

raw_data_2 |> 
  pivot_longer(-category) |> 
  separate(name, into = c("prefix", "year")) |> 
  complete(category, prefix, year) |> 
  pivot_wider(names_from = c("prefix", "year"))

output

# A tibble: 3 × 7
  category a_2022 a_2023 b_2022 b_2023 e_2022 e_2023
  <chr>     <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 A             1    1.5    0.1     NA     NA    0.3
2 B             2    3      0.4     NA     NA    0.7
3 C             3    4      0.3     NA     NA    0.5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading