如何创建一个表格,为R中的分组值创建单独的条目

时间:2018-08-08 18:10:13

标签: r

让我们说我有一个如下数据框:

data <- data.frame("Company" = c("X", "Y"),
                   "Chocolate" = c(1, 2),
                   "Vanilla" = c(2 ,1))
data

  Company Chocolate Vanilla
1       X         1       2
2       Y         2       1

如何将data.frame重塑为以下格式:

Company    Type
  X        "Chocolate"
  X        "Vanilla"
  X        "Vanilla"
  Y        "Chocolate"
  Y        "Chocolate"
  Y        "Vanilla"

我试图制作一个空的数据框,然后以某种方式使用“ for”循环,但是我很难理解如何使其工作

1 个答案:

答案 0 :(得分:1)

如果您愿意使用某些软件包,可以

library(dplyr)
library(tidyr)
library(splitstackshape)

data %>% 
  gather(Type, freq, -Company) %>% # Change the structure to have the types in a column for type
  expandRows("freq") %>% # Repeat each row how many times indicated
  arrange(Company) # Sort by company

  Company      Type
1       X Chocolate
2       X   Vanilla
3       X   Vanilla
4       Y Chocolate
5       Y Chocolate
6       Y   Vanilla