Home > Mobile >  Reshape one column to multiple columns in R
Reshape one column to multiple columns in R

Time:10-07

I have a dataframe such as :

Groups COL1
G1     1
G2     3
G3     5
G1     7
G2     9
G3     11

And I would like to take the column Groups as multiple unique colums such as :

       G1 G2 G3 
  1    1  3  5
  2    7  9  8

Does someone have an idea please ?

Here is the toy data if it can helps :

structure(list(Groups = c("G1", "G2", "G3", "G1", "G2", "G3"), 
    Col1 = c(1L, 3L, 5L, 7L, 9L, 11L)), class = "data.frame", row.names = c(NA, 
-6L))

CodePudding user response:

After your edits, here's a dplyr and tidyr solution:

library(tidyverse)
df %>% 
  pivot_wider(names_from = Groups,
              values_from = Col1,
              values_fn = list) %>% 
  unnest(cols = c(G1,G2,G3))

Output:

     G1    G2    G3
  <int> <int> <int>
1     1     3     5
2     7     9    11

Data used:

df <- structure(list(Groups = c("G1", "G2", "G3", "G1", "G2", "G3"), 
    Col1 = c(1L, 3L, 5L, 7L, 9L, 11L)), class = "data.frame", row.names = c(NA, 
-6L))

CodePudding user response:

Another idea is:

df %>%
  group_by(Groups) %>%
  mutate(index = row_number()) %>%
  pivot_wider(names_from = "Groups", values_from = "Col1")

# A tibble: 2 x 4
  index    G1    G2    G3
  <int> <int> <int> <int>
1     1     1     3     5
2     2     7     9    11

Can drop index in the end

CodePudding user response:

We may use unstack from base R

unstack(df, Col1 ~ Groups)
  G1 G2 G3
1  1  3  5
2  7  9 11
  • Related