简体   繁体   English

如何将数据从长格式重塑为宽格式以实现此输出?

[英]How to reshape data from long to wide format so to achieve this output?

I'm having trouble rearranging the following data frame with tidyr package:我在使用tidyr包重新排列以下数据框时tidyr

data <- data.frame(
    name = rep(c("John", "Mary", "Peter", "Sarah"), each=2),
    firm = c("a", "b", "c", "d", "a", "b", "c", "d"),
    rank = rep(1:2, 4),
    value = rnorm(8)
    )

I want to reshape it so that each unique "name" variable is a rowname, with the "values" as observations along that row and the "rank" as colnames followed by the "firm" name.我想重塑它,以便每个唯一的“名称”变量都是一个行名,“值”作为该行的观察值,“排名”作为列名,后跟“公司”名称。 Sort of like this:有点像这样:

  name          1      firm_1            2       firm_2
  John       0.3407997      a        -0.3795377      b
  Mary      -0.8981073      c       -0.5013782       d
  Peter     0.3407997       a        -0.3795377      b
  Sarah     -0.8981073      c       -0.5013782       d

We can use a combination of dplyr and tidyr , similarly to the posts in the comment by @aosmith.我们可以使用dplyrtidyr的组合,类似于@aosmith 评论中的帖子。

library(dplyr) # [1] ‘1.0.0’
library(tidyr) # [1] ‘1.1.0’

data %>% pivot_wider(names_from = rank, values_from = c(firm, value)) %>%
        select(name, `1` = value_1, firm_1, `2` = value_2, firm_2)

In order to fully go from long to wide format we must take values_from not 1, but 2, columns, as the original data has 4, not 3, columns.为了完全从长格式到宽格式,我们必须采用values_from而不是 1 列,而是 2 列,因为原始data有 4 列,而不是 3 列。

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

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