devbasic
devbasic

Reputation: 41

convert one column of many rows into many columns

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

Upvotes: 0

Views: 63

Answers (3)

akrun
akrun

Reputation: 887118

Using unstack in base R

unstack(df1, ColumnB~ ColumnA)
  Apple Bat Cat
1     2 2.0 4.0
2     6 2.5 4.8

data

df1 <- structure(list(ColumnA = c("Apple", "Bat", "Cat", "Bat", "Apple", 
"Cat"), ColumnB = c(2, 2, 4, 2.5, 6, 4.8)), class = "data.frame", 
row.names = c(NA, 
-6L))

Upvotes: 1

cgvoller
cgvoller

Reputation: 879

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

Upvotes: 1

TarJae
TarJae

Reputation: 78927

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
> 

Upvotes: 1

Related Questions