将行转置并分组为列,列作为R中的相应值[重复]

wnrlj8wa  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(123)
    • 此问题在此处已有答案**:

How to reshape data from long to wide format(14个答案)
2天前关闭。
我想把一个大的日期框架转换成一个小的。这样就把相似的行分组,并把另一行转置成多个列,其中每行的值变成列的值。
我的table就是这个样子

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)

我试过了,但我不知道如何将行转换为列。

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 = ',')

这就是我要找的
∮我想要的∮

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)
bqf10yzr

bqf10yzr1#

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

相关问题