Home > OS >  Pivot in R and keep other columns
Pivot in R and keep other columns

Time:10-13

I have the following df in R:

ID_A Value_A Boolean Value_B
1 0.2 1 -2
1 0.1 0 -2
2 0.5 1 1
2 -0.3 0 1

And I want the following output:

ID_A Value_A_Boo_1 Value_A_Boo_0 Value_B
1 0.2 0.1 -2
2 0.5 -0.3 1

I think that is has something to do with pivot, but I am always loosing some of the informations of other columns. Basically I just want to modify Value A based on Boolean-column and keep ID_A and Value_B.

CodePudding user response:

This is indeed a pivot to wide. You can use pivot_wider from tidyr. Check the names_glue argument, very useful to construct the new column names.

library(tidyr)
df %>% 
  pivot_wider(names_from = "Boolean", values_from = "Value_A", 
              names_glue = "{.value}_Boo_{Boolean}")

# A tibble: 2 × 4
   ID_A Value_B Value_A_Boo_1 Value_A_Boo_0
  <int>   <int>         <dbl>         <dbl>
1     1      -2           0.2           0.1
2     2       1           0.5          -0.3
  • Related