OTA
OTA

Reputation: 279

I have a column with multiple groups. I want each group as its own column

I have a dataframe with two columns. The first column has the groups, and the second column has values.

I want each grouping to be a column, and I want all associated values under the appropriate column.

I prefer a tidyverse solution. If possible, I prefer a solution that automatically takes each group and creates a new column with the appropriate values under it. I do not want to manually type the headers.

This is what I have:

df <- data.frame(Group = c("A", "A", "A", "B", "B", "B"),
                 Value = c(2,2,2,3,3,3))
df$Group <- as.character(df$Group)

This is what I want:

want <- data.frame(A = c(2,2,2),
                   B = c(3,3,3))

Upvotes: 2

Views: 663

Answers (1)

akrun
akrun

Reputation: 887118

With tidyverse, we can use pivot_wider after creating a sequence column by 'Group'

library(dplyr)
library(tidyr)
df %>% 
   group_by(Group) %>%
   mutate(rn = row_number()) %>% 
   pivot_wider(names_from = Group, values_from = Value) %>%
   select(-rn)
# A tibble: 3 x 2
#      A     B
#  <dbl> <dbl>
#1     2     3
#2     2     3
#3     2     3

In base R, it can be one with unstack

unstack(df, Value ~ Group)

Or with data.table

library(data.table)
dcast(setDT(df), rowid(Group) ~ Group, value.var = 'Value')[, .(A, B)]

Upvotes: 2

Related Questions