gpt4 book ai didi

r - 是否有一个 R 函数可以将这些数据从长变宽?

转载 作者:行者123 更新时间:2023-12-04 22:23:41 25 4
gpt4 key购买 nike

数据现在的样子:

Coach ID | Student | score |
---------------------------------
1 | A | 8 |
1 | B | 3 |
2 | A | 5 |
2 | B | 4 |
2 | C | 7 |

看起来像这样:
Coach ID | Student | score | student_2|score_2| student_3|score_3
------------------------------------------------------------------
1 | A | 8 | B | 3 |
2 | A | 5 | B | 4 | C | 7

反正有没有将数据从长到宽 reshape ?

谢谢!

最佳答案

您可以为每个 student 创建一个具有唯一值的新标识符列然后使用 pivot_wider将多个列设置为宽。

library(dplyr)
df %>%
mutate(name = as.integer(factor(Student))) %>%
tidyr::pivot_wider(names_from = name, values_from = c(Student, score))

# CoachID Student_1 Student_2 Student_3 score_1 score_2 score_3
# <int> <fct> <fct> <fct> <int> <int> <int>
#1 1 A B NA 8 3 NA
#2 2 A B C 5 4 7

数据
df <- structure(list(CoachID = c(1L, 1L, 2L, 2L, 2L), Student = structure(c(1L, 
2L, 1L, 2L, 3L), .Label = c("A", "B", "C"), class = "factor"),
score = c(8L, 3L, 5L, 4L, 7L)), class = "data.frame", row.names = c(NA, -5L))

关于r - 是否有一个 R 函数可以将这些数据从长变宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60087414/

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