我有一个聚合表:
> 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
Run Code Online (Sandbox Code Playgroud)
当我有Group.1和Group.2的值时,如何选择x值?
我试过了:
aggdata[aggdata[,"Group.1"]==l && aggdata[,"Group.2"]==lamda,"x"]
Run Code Online (Sandbox Code Playgroud)
但那回复所有的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"]
}
}
Run Code Online (Sandbox Code Playgroud)
任何更容易的建议,并给予这个结果,我很感激!
Ken*_*ams 22
最简单的解决方案是在代码中将"&&"更改为"&".
> aggdata[aggdata[,"Group.1"]==6 & aggdata[,"Group.2"]==0.05,"x"]
[1] 0.9315789
Run Code Online (Sandbox Code Playgroud)
我首选的解决方案是使用subset():
> subset(aggdata, Group.1==6 & Group.2==0.05)$x
[1] 0.9315789
Run Code Online (Sandbox Code Playgroud)
Rob*_*man 13
使用&不是&&.后者仅评估每个向量的第一个元素.
更新:要回答第二部分,请使用重塑包.像这样的东西会这样做:
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]
Run Code Online (Sandbox Code Playgroud)
有更多使用重塑经验的人可能会有一个更简单的解决方案.
注意:不要将table用作变量名,因为它与table()函数冲突.
小智 8
关于R数据框的子集有一个非常有用的文档:http: //www.ats.ucla.edu/stat/r/modules/subsetting.htm
以下是相关摘录:
使用多个条件语句对行进行子集:对可以组合多少个逻辑语句以实现所需的子集没有限制.数据帧x.sub1仅包含变量y的值大于2且变量V1大于0.6的观测值.
x.sub1 <- subset(x.df, y > 2 & V1 > 0.6)