根据另一列提取值 [英] 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
但是当没有FALSE值时,我得到
but when there are no FALSE values, I get
x freq
1 TRUE 46
当x = TRUE时,我想提取频率值. 如果总是同时存在FALSE和TRUE值,我可以做
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
但是无论是否存在FALSE值,我都希望能够提取TRUE值.有人知道我该怎么做吗?预先感谢!
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!
推荐答案
正如@Justin所说,您可能正在使用data.frame
而不是matrix
.一切都好.使用上面的示例,如果您的data.frame看起来如下:
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
无论是否存在FALSE
值,以下内容都会为您提供所需的信息.
The following will get you what you want irrespective of whether there are FALSE
values or not.
df$freq[df$x==TRUE]
[1] 6
编辑:正如@DWin所指出的,您可以使用df$x
是合乎逻辑的事实来进一步简化:
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
例如:
> df2 <- data.frame(x=TRUE, freq=46)
> df2
x freq
1 TRUE 46
仍然有效:
> df2$freq[df2$x==TRUE]
[1] 46
这篇关于根据另一列提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!