gpt4 book ai didi

r - 如何从具有 2 个条件的 data.frame 中选择行

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

我有一个汇总表:

> aggdata[1:4,]
Group.1 Group.2 x
1 4 0.05 0.9214660
2 6 0.05 0.9315789
3 8 0.05 0.9526316
4 10 0.05 0.9684211

当我有 Group.1 和 Group.2 的值时,如何选择 x 值?

我试过:
aggdata[aggdata[,"Group.1"]==l && aggdata[,"Group.2"]==lamda,"x"]

但这回答了所有x。

更多信息:
我想这样使用它:
table = data.frame();
for(l in unique(aggdata[,"Group.1"])) {
for(lambda in unique(aggdata[,"Group.2"])) {
table[l,lambda] = aggdata[aggdata[,"Group.1"]==l & aggdata[,"Group.2"]==lambda,"x"]
}
}

任何更容易并给出这个结果的建议,我很感激!

最佳答案

使用 & 而非 &&。后者只计算每个向量的第一个元素。

更新:要回答第二部分,请使用 reshape 包。像这样的事情会做到:

tablex <- recast(aggdata, Group.1 ~ variable * Group.2, id.var=1:2)
# Now add useful column and row names
colnames(tablex) <- gsub("x_","",colnames(tablex))
rownames(tablex) <- tablex[,1]
# Finally remove the redundant first column
tablex <- tablex[,-1]

使用 reshape 有更多经验的人可能有更简单的解决方案。

注意:不要使用 table 作为变量名,因为它与 table() 函数冲突。

关于r - 如何从具有 2 个条件的 data.frame 中选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1536590/

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