Search code examples
rdataframemultiple-columnstranspose

Transpose and group by rows into columns with a column as the respective value in R


I want to convert a large date frame into a smaller one. Thus grouping rows that are similar and transposing another row into multiple columns, where the values for each row become the value for the columns.

This is what my table looks like

Gemeinde <- c("Adliswil", "Adliswil", "Adliswil", "Adliswil", "Adliswil","Adlikon", "Adlikon", "Adlikon", "Adlikon", "Adlikon")
Country <- c("Schweiz", "Deutschland", "Frankreich", "Italien", "China","Schweiz", "Deutschland", "Frankreich", "Italien", "China")
Count <- c(23, 41, 32, 58, 26,23, 41, 32, 58, 26)

df <- data.frame(Gemeinde, Country, Count)

print (df)

I tried this, but I don't understand how to convert the row to columns.

df_SO <- df %>%
  mutate(rn = row_number()) %>%
  group_by(Gemeinde) %>% 
  pivot_wider(id_cols = c(Gemeinde, rn), names_from = Country, values_from = Count) %>%
  as.data.frame() %>%
  select(-rn) %>%
  mutate_all(~(.[order(is.na(.))])) %>%
  filter_all(any_vars(!is.na(.))) %>%
  unite(result, everything(), sep = ',')

This is what I am looking for

What I want

Gemeinde <- c("Adliswil", "Adlikon")
Schweiz <- 23
Deutschland <- 41
Frankreich <- 32
Italien<- 58
China<- 26

df <- data.frame(Gemeinde, Schweiz, Deutschland, Frankreich, Italien, China)

print (df)

Solution

  • library(tidyverse)
    df %>% pivot_wider(names_from = Country,
                       values_from = Count)