gpt4 book ai didi

reshape - 防止分类变量在列上重复

转载 作者:行者123 更新时间:2023-12-02 08:29:11 24 4
gpt4 key购买 nike

<分区>

我想把一张 table 从长改成宽。它有多个值和一个分类变量。

表格看起来像:

df <- data.frame(name = c("john", "mary", "john", "mary"), 
variable = c("math", "math", "science", "science"),
grade = c("sixth", "sixth", "sixth", "sixth"),
val1 = c(78, 88, 97, 100), val2 = c(92, 83, 69, 94))

我想要的是:

want <- data.frame(name = c("john", "mary"), grade = c("sixth", "sixth"),
math.val1 = c(78, 88), math.val2 = c(92, 83), science.val1 = c(97, 100),
science.val2 = c(69, 94))

没有成绩列,我可以轻松实现:

reshape(df, idvar='name', timevar='variable', direction='wide')

通过“等级”列,我得到:

  name grade.math val1.math val2.math grade.science val1.science val2.science
1 john sixth 78 92 sixth 97 69
2 mary sixth 88 83 sixth 100 94

我该如何纠正这个问题?

谢谢。

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