gpt4 book ai didi

r - 融化数据的列算术等价物

转载 作者:行者123 更新时间:2023-12-04 18:23:55 33 4
gpt4 key购买 nike

我有一个像这样的“整洁”格式的数据集:

  group         type score price
1 A Fish + Chips 9 8
2 B Fish + Chips 7 20
3 C Fish + Chips 8 22
4 A Chips 9 0
5 B Chips 0 7
6 C Chips 8 16
7 A Snags 5 19
8 B Snags 9 8
9 C Snags 10 6

我想添加一些派生数据,如果将数据转换为宽格式,将使用列算法(加法、减法等)确定这些数据。我一直在努力研究如何在不再次类型转换和熔化的情况下做到这一点。在这里的简单示例中,我想通过从相应的 Fish + Chips 数据中减去 Chips 数据来计算 Fish 类型的数据。到目前为止,我已经想出了以下内容:

ddply(subset(mydata, type %in% c("Chips", "Fish + Chips")),
.(group), summarise, type="Fish",
score=score[type=="Fish + Chips"] - score[type=="Chips"],
price=price[type=="Fish + Chips"] - price[type=="Chips"])

给出

  group type score price
1 A Fish 0 8
2 B Fish 7 13
3 C Fish 0 6

然后我可以将其 rbind 到原始数据。任何关于更好方法的建议都将不胜感激(即使那是类型转换和熔化)。

这是示例数据:

structure(list(group = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
2L, 3L), .Label = c("A", "B", "C"), class = "factor"), type = structure(c(2L,
2L, 2L, 1L, 1L, 1L, 3L, 3L, 3L), .Label = c("Chips", "Fish + Chips",
"Snags"), class = "factor"), score = c(9, 7, 8, 9, 0, 8, 5, 9,
10), price = c(8, 20, 22, 0, 7, 16, 19, 8, 6)), .Names = c("group",
"type", "score", "price"), row.names = c(NA, -9L), class = "data.frame")

最佳答案

我认为你的更好,但这里有一个非 plyr/reshape 解决方案:

mydataspl <- split(mydata, mydata$type)
subs <- merge(mydataspl$"Fish + Chips", mydataspl$Chips, by= 1)
data.frame(subs[,"group", drop=FALSE], type="Fish",
score=with(subs, score.x-score.y),
price=with(subs, price.x-price.y)
)
group type score price
1 A Fish 0 8
2 B Fish 7 13
3 C Fish 0 6

关于r - 融化数据的列算术等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12100833/

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