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
458 views
in Technique[技术] by (71.8m points)

r - extracting value based on another column

I have a function that spits out a matrix, such as:

      x freq
1 FALSE   40
2  TRUE    6

but when there are no FALSE values, I get

     x freq
1 TRUE   46

I want to extract the freq value when x=TRUE. If there are are always both FALSE and TRUE values, I can do

> matrix [2,2]
[1] 6

But I would like to be able to extract the TRUE value whether or not there are FALSE values. Does anyone know how I can do that? Thanks in advance!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As @Justin said, you might be working with a data.frame instead of a matrix. All the better. Using your example above, if your data.frame looks as follows:

df <- data.frame(x=c(FALSE,TRUE), freq=c(40, 6))
> df
      x freq
1 FALSE   40
2  TRUE    6

The following will get you what you want irrespective of whether there are FALSE values or not.

df$freq[df$x==TRUE]
[1] 6

EDIT: As @DWin points out, you can simplify further by using the fact that df$x is logical:

> df$freq[df$x]
[1] 6
> df$freq[!df$x]
[1] 40

For example:

> df2 <- data.frame(x=TRUE, freq=46)
> df2
     x freq
1 TRUE   46

Still works:

> df2$freq[df2$x==TRUE]
[1] 46

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

...