Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

r - How to select rows from data.frame with 2 conditions

I have an aggregated table:

> 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

How can I select the x value when I have values for Group.1 and Group.2?

I tried:

aggdata[aggdata[,"Group.1"]==l && aggdata[,"Group.2"]==lamda,"x"]

but that replies all x's.

More info: I want to use this like this:

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"]
    }
}

Any suggestions that are even easier and giving this result I appreciate!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest solution is to change "&&" to "&" in your code.

> aggdata[aggdata[,"Group.1"]==6 & aggdata[,"Group.2"]==0.05,"x"]
[1] 0.9315789

My preferred solution would be to use subset():

> subset(aggdata, Group.1==6 & Group.2==0.05)$x
[1] 0.9315789

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...