简体   繁体   English

在 R 中将表格从长格式重塑为宽格式

[英]Reshaping tables from long to wide format in R

set inst研究所 ind工业 color_Blue颜色_蓝色
1 1个 0 0 0 0 70 70
1 1个 0 0 1 1个 60 60
1 1个 0 0 2 2个 50 50
1 1个 1 1个 0 0 30 30
1 1个 1 1个 1 1个 20 20
1 1个 1 1个 2 2个 66 66
2 2个 0 0 0 0 35 35
2 2个 0 0 1 1个 22 22
2 2个 0 0 2 2个 28 28
2 2个 1 1个 0 0 90 90后
2 2个 1 1个 1 1个 47 47
2 2个 1 1个 2 2个 23 23

I have data frame looks like this above and I want to convert this to:我的数据框看起来像上面这样,我想将其转换为:

ind工业 set inst_0 inst_0 inst_1 inst_1 inst_2 inst_2
0 0 1 1个 70 70 60 60 50 50
1 1个 1 1个 30 30 20 20 66 66
2 2个 1 1个 35 35 22 22 28 28
0 0 2 2个 90 90后 47 47 23 23
1 1个 2 2个 .. .. .. .. .. ..
2 2个 2 2个 .. .. .. .. .. ..

How can I do this transform?我怎样才能做这个转变? I would appreciate any suggestion.我将不胜感激任何建议。 Thank you so much!太感谢了!

I have tried some things but did not really work.I have to do the change based on two columns information and that was confusing me.我尝试了一些方法但没有真正起作用。我必须根据两列信息进行更改,这让我很困惑。

You can use pivot_wider() from tidyr for reshaping.您可以使用 tidyr 中的tidyr pivot_wider()进行重塑。

library(tidyr)

df %>%
  pivot_wider(names_from = ind, values_from = color_Blue, names_prefix = 'inst_')

# # A tibble: 4 × 5
#     set  inst inst_0 inst_1 inst_2
#   <int> <int>  <int>  <int>  <int>
# 1     1     0     70     60     50
# 2     1     1     30     20     66
# 3     2     0     35     22     28
# 4     2     1     90     47     23
Data数据
df <- read.table(text = "
set inst    ind color_Blue
1   0   0   70
1   0   1   60
1   0   2   50
1   1   0   30
1   1   1   20
1   1   2   66
2   0   0   35
2   0   1   22
2   0   2   28
2   1   0   90
2   1   1   47
2   1   2   23", header = TRUE)

data.table data.table

df <- read.table(text = "set    inst    ind color_Blue
1   0   0   70
1   0   1   60
1   0   2   50
1   1   0   30
1   1   1   20
1   1   2   66
2   0   0   35
2   0   1   22
2   0   2   28
2   1   0   90
2   1   1   47
2   1   2   23", header = T)

library(data.table)
dcast(
  data = setDT(df),
  formula = inst + set ~ paste0("inst_", ind),
  value.var = "color_Blue"
)
#>    inst set inst_0 inst_1 inst_2
#> 1:    0   1     70     60     50
#> 2:    0   2     35     22     28
#> 3:    1   1     30     20     66
#> 4:    1   2     90     47     23

Created on 2023-01-19 with reprex v2.0.2创建于 2023-01-19,使用reprex v2.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM