gpt4 book ai didi

在 R 中 reshape 数据。是否可以有两个 "value variables"

转载 作者:行者123 更新时间:2023-12-04 09:28:24 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Reshaping several variables wide with cast

(3 个回答)


7年前关闭。




我正在努力 reshape 包,寻找一种“转换”数据框但在“value.var”中有两个(或更多)值的方法。

这是我想要实现的一个例子。

df <- data.frame( StudentID = c("x1", "x10", "x2", 
"x3", "x4", "x5", "x6", "x7", "x8", "x9"),
StudentGender = c('F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'),
ExamenYear = c('2007','2007','2007','2008','2008','2008','2008','2009','2009','2009'),
Exam = c('algebra', 'stats', 'bio', 'algebra', 'algebra', 'stats', 'stats', 'algebra', 'bio', 'bio'),
participated = c('no','yes','yes','yes','no','yes','yes','yes','yes','yes'),
passed = c('no','yes','yes','yes','no','yes','yes','yes','no','yes'),
stringsAsFactors = FALSE)

从 df 我可以创建以下数据框:
tx <- ddply(df, c('ExamenYear','StudentGender'), summarize,
participated = sum(participated == "yes"),
passed = sum(passed == "yes"))

在 reshape 逻辑中,我有两个 “值(value)变量”参加并通过

我正在寻找将以下信息组合在一个数据框中的方法:
 dcast(tx, formula = ExamenYear ~ StudentGender, value.var = 'participated')
dcast(tx, formula = ExamenYear ~ StudentGender, value.var = 'passed')

我试图创建的茶几看起来像这样
tempTab1 <- dcast(tx, formula = ExamenYear ~ StudentGender, value.var = 'participated')
tempTab2 <- dcast(tx, formula = ExamenYear ~ StudentGender, value.var = 'passed')

as.data.frame(cbind(ExamenYear = tempTab1[,1],
Female_Participated = tempTab1[,2],
Female_Passed = tempTab2[,2],
Male_Participated = tempTab1[,3],
Male_Passed = tempTab2[,3]
))

转换函数中是否可以有两个“值变量”?

最佳答案

既然你已经走到这一步,何不melt您的 tx反对和使用dcast如下:

dcast(melt(tx, id.vars=c(1, 2)), ExamenYear ~ StudentGender + variable)
# ExamenYear F_participated F_passed M_participated M_passed
# 1 2007 1 1 1 1
# 2 2008 1 1 2 2
# 3 2009 NA NA 3 2

然而,更直接的方法可能是 melt。您从一开始的数据:
df.m <- melt(df, id.vars=c(1:4))
dcast(df.m, ExamenYear ~ StudentGender + variable,
function(x) sum(x == "yes"))
# ExamenYear F_participated F_passed M_participated M_passed
# 1 2007 1 1 1 1
# 2 2008 1 1 2 2
# 3 2009 0 0 3 2

更新:基础 R 方法

虽然所需的代码没有那么“漂亮”,但在基础 R 中执行此操作也不是太难。这是一种方法:
  • 使用aggregate()获取 tx从你的例子。
    dfa <- aggregate(cbind(participated, passed) ~ 
    ExamenYear + StudentGender, df, function(x) sum(x == "yes"))
    dfa
    # ExamenYear StudentGender participated passed
    # 1 2007 F 1 1
    # 2 2008 F 1 1
    # 3 2007 M 1 1
    # 4 2008 M 2 2
    # 5 2009 M 3 2
  • 使用reshape改造dfa从“长”到“宽”。
    reshape(dfa, direction = "wide", 
    idvar="ExamenYear", timevar="StudentGender")
    # ExamenYear participated.F passed.F participated.M passed.M
    # 1 2007 1 1 1 1
    # 2 2008 1 1 2 2
    # 5 2009 NA NA 3 2
  • 关于在 R 中 reshape 数据。是否可以有两个 "value variables",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12437012/

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