R从长到宽格式重塑数据帧?

时间:2018-06-08 16:57:49

标签: r dataframe reshape

将数据框从长格式转换为宽格式的最佳方法是什么?我尝试使用重塑,但没有得到预期的结果。

2015    PROD A  test1
2015    PROD A  blue
2015    PROD A  50
2015    PROD A  66
2015    PROD A  66
2018    PROD B  test2
2018    PROD B  yellow
2018    PROD B  70
2018    PROD B  88.8
2018    PROD B  88.8
2018    PROD A  test3
2018    PROD A  red
2018    PROD A  55
2018    PROD A  88
2018    PROD A  90

enter image description here

3 个答案:

答案 0 :(得分:2)

可能的解决方案是

library(tidyverse)

df = read.table(text = "
                year prod value
                2015    PRODA  test1
                2015    PRODA  blue
                2015    PRODA  50
                2015    PRODA  66
                2015    PRODA  66
                2018    PRODB  test2
                2018    PRODB  yellow
                2018    PRODB  70
                2018    PRODB  88.8
                2018    PRODB  88.8
                2018    PRODA  test3
                2018    PRODA  red
                2018    PRODA  55
                2018    PRODA  88
                2018    PRODA  90
                ", header=T, stringsAsFactors=F)

df %>%
  group_by(year, prod) %>%                           # for each year and prod combination
  mutate(id = paste0("new_col_", row_number())) %>%  # enumerate rows (this will be used as column names in the reshaped version)
  ungroup() %>%                                      # forget the grouping
  spread(id, value)                                  # reshape

# # A tibble: 3 x 7
#    year prod  new_col_1 new_col_2 new_col_3 new_col_4 new_col_5
#   <int> <chr> <chr>     <chr>     <chr>     <chr>     <chr>    
# 1  2015 PRODA test1     blue      50        66        66       
# 2  2018 PRODA test3     red       55        88        90       
# 3  2018 PRODB test2     yellow    70        88.8      88.8 

答案 1 :(得分:1)

出于完整性考虑,以下是使用xxx: ["fsd,das"] 方便的data.table函数的解决方案。

问题的关键在于,重塑仅取决于每个(rowid()value)组中year行位置product为每个组中的行编号。因此,重塑本质上变成了单线:

rowid(year, product)
library(data.table)
dcast(setDT(df1), year + product ~ rowid(year, product, prefix = "col_"))

请注意, year product col_1 col_2 col_3 col_4 col_5 1: 2015 PROD A test1 blue 50 66 66 2: 2018 PROD A test3 red 55 88 90 3: 2018 PROD B test2 yellow 70 88.8 88.8 使用一个rowid()参数来确保结果列名称在语法上是正确的。

注意事项:该解决方案假定prefixyear为每个组形成一个唯一键

数据

OP会按原样读取数据,而无需对数据进行任何修改。但是,这需要几行后处理:

product

答案 2 :(得分:-1)

您正在寻找dcast功能。使用如下:

dcast(data, col1 + col2 ~ col3)

此问题也可能重复,因此可能会被删除。

相关问题