Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...