gpt4 book ai didi

r - 如何将多个变量的重复测量扩展到宽格式?

转载 作者:行者123 更新时间:2023-12-03 05:35:16 25 4
gpt4 key购买 nike

我正在尝试将长格式的列展开为宽格式,如下所示。我想使用 tidyr 来通过我正在投资的数据操作工具来解决这个问题,但为了使这个答案更通用,请提供其他解决方案。

这是我所拥有的:

library(dplyr); library(tidyr)

set.seed(10)
dat <- data_frame(
Person = rep(c("greg", "sally", "sue"), each=2),
Time = rep(c("Pre", "Post"), 3),
Score1 = round(rnorm(6, mean = 80, sd=4), 0),
Score2 = round(jitter(Score1, 15), 0),
Score3 = 5 + (Score1 + Score2)/2
)

## Person Time Score1 Score2 Score3
## 1 greg Pre 80 78 84.0
## 2 greg Post 79 80 84.5
## 3 sally Pre 75 74 79.5
## 4 sally Post 78 78 83.0
## 5 sue Pre 81 78 84.5
## 6 sue Post 82 81 86.5

所需的宽格式:

  Person Pre.Score1 Pre.Score2 Pre.Score3  Post.Score1 Post.Score2 Post.Score3
1 greg 80 78 84.0 79 80 84.5
2 sally 75 74 79.5 78 78 83.0
3 sue 81 78 84.5 82 81 86.5

我可以通过对每个分数执行类似的操作来做到这一点:

spread(dat %>% select(Person, Time, Score1), Time, Score1) %>% 
rename(Score1_Pre = Pre, Score1_Post = Post)

然后使用 _join 但这看起来很冗长,而且好像必须有更好的方法。

相关问题:
tidyr wide to long with two repeated measures
Is it possible to use spread on multiple columns in tidyr similar to dcast?

最佳答案

编辑:我正在更新这个答案,因为pivot_wider已经存在了一段时间并解决了这个问题和评论中的问题。您现在可以这样做

pivot_wider(
dat,
id_cols = 'Person',
names_from = 'Time',
values_from = c('Score1', 'Score2', 'Score3'),
names_glue = '{Time}.{.value}'
)

得到想要的结果。

<小时/>

原来的答案是

dat %>% 
gather(temp, score, starts_with("Score")) %>%
unite(temp1, Time, temp, sep = ".") %>%
spread(temp1, score)

关于r - 如何将多个变量的重复测量扩展到宽格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com