Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting value based on another column

Tags:

r

extract

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!

like image 828
EricaO Avatar asked Sep 09 '13 20:09

EricaO


1 Answers

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
like image 130
harkmug Avatar answered Sep 22 '22 01:09

harkmug