Home > Blockchain >  convert one column of many rows into many columns
convert one column of many rows into many columns

Time:11-17

I've a two columns in a file, like this

Column A Column B
Apple 2
Bat 2
Cat 4
Bat 2.5
Apple 6
Cat 4.8

I want to covert Column A values into individual columns & corresponding values from Column B

Apple Bat Cat
2 2 4
6 2.5 4.8

CodePudding user response:

As you said you have more than 3, this should work for any amount in column A

library(dplyr)
library(tidyr)



 df <-
  data.frame(
    ColA = c("A", "B", "C", "B", "A", "C", "D", "E","D","E"),
    ColB = c(2, 2, 4, 2.5, 6, 4.8, 6, 2,3,2)
  )

 df %>% dplyr::group_by(ColA) %>%
  dplyr::mutate(row = row_number()) %>% 
  tidyr::pivot_wider(names_from = ColA, values_from = ColB) %>%
  dplyr::select(-row)

Output:

# A tibble: 2 × 5
      A     B     C     D     E
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     2   2     4       6     2
2     6   2.5   4.8     3     2

CodePudding user response:

For your data, we could do it this way:

Most important is to create groups with n (in this case 3), we do it with the first row using gl() function, then we use pivot_wider:

library(dplyr)
library(tidyr)

df %>% 
  mutate(col2 =as.integer(gl(n(),3,n()))) %>% 
  pivot_wider(names_from = ColumnA, values_from=ColumnB) %>% 
  select(-col2)
  Apple   Bat   Cat
  <dbl> <dbl> <dbl>
1     2   2     4  
2     6   2.5   4.8
> 
  •  Tags:  
  • r
  • Related