extracting value based on another column

后端 未结 1 1844
执念已碎
执念已碎 2021-01-03 03:00

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

<
1条回答
  •  执念已碎
    2021-01-03 03:28

    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
    

    0 讨论(0)
提交回复
热议问题