【问题标题】:R - Convert and transpose data to columns by group [duplicate]R - 按组将数据转换并转置为列[重复]
【发布时间】:2018-12-15 01:49:15
【问题描述】:

在通过尝试 tidyr、reshape、spread 等几个小时努力解决这一挑战后,我非常感谢 R 专家的帮助。

对于不同组和分配值的数据框,有没有办法转换和转置数据框,以便将每个组分配给一个新列,并且所有分配的值都列在该组下?

以下是数据框的一些示例代码:

a <- c("Group1", "Group1", "Group1", "Group2", "Group2", "Group2", "Group2", "Group2", "Group3")
b <- c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9") 

使用这两列,为每个组创建一个新列。

下面,我手动显示,但需要 R 自动执行下一步。

我手动包含“--”以避免错误“data.frame 中的错误:参数意味着不同的行数”。实际上,我无法为每个组添加“--”。

Group1 <- c("Item1", "Item2", "Item3", "--", "--")
Group2 <- c("Item4", "Item5", "Item6", "Item7", "Item8")
Group3 <- c("Item9", "--", "--", "--", "--")

下面,这是我要创建的输出。

table <- data.frame(Group1, Group2, Group3)

挑战在于变量必须是动态的。不同数据集的组数和项目数会发生变化,我无法为每个组中的空白手动“--”。

这个问题类似于这个问题,除了我的问题涉及动态范围。 Convert data frame common rows to columns

【问题讨论】:

  • 这里的反对意见并不合理。
  • 链接的重复答案没有解决这里的情况,“参数意味着不同的行数”错误。

标签: r reshape reshape2


【解决方案1】:

我们可以使用tidyr::spread

library(tidyverse)
df %>% group_by(a) %>% mutate(n = 1:n()) %>% spread(a, b) %>% select(-n)
## A tibble: 5 x 3
#  Group1 Group2 Group3
#  <fct>  <fct>  <fct>
#1 Item1  Item4  Item9
#2 Item2  Item5  NA
#3 Item3  Item6  NA
#4 NA     Item7  NA
#5 NA     Item8  NA

或者,如果您更喜欢 "--" 而不是 NA,您可以这样做(感谢 @AntoniosK)

df %>%
    group_by(a) %>%
    mutate(n = 1:n()) %>%
    spread(a, b) %>%
    select(-n) %>%
    mutate_all(~ifelse(is.na(.), "--", as.character(.)))
## A tibble: 5 x 3
#  Group1 Group2 Group3
#  <chr>  <chr>  <chr>
#1 Item1  Item4  Item9
#2 Item2  Item5  --
#3 Item3  Item6  --
#4 --     Item7  --
#5 --     Item8  --

或使用tidyr::spreads fill 参数

df %>%
    mutate_if(is.factor, as.character) %>%
    group_by(a) %>%
    mutate(n = 1:n()) %>%
    spread(a, b, fill = "--") %>%
    select(-n)

给出相同的结果。


样本数据

a <- c("Group1", "Group1", "Group1", "Group2", "Group2", "Group2", "Group2", "Group2", "Group3")
b <- c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")
df <- data.frame(a = a, b = b)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-08
    • 2019-03-02
    • 2021-06-25
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2018-08-19
    • 2020-02-16
    相关资源
    最近更新 更多