根据相同数据框的逻辑获取列名的向量
我有一个命名的dataframe containig逻辑逻辑,我想获得一个带有列名的向量,其中值为true
(向下行,如果多个true> true
在一排,从左到右)。这里一个示例:
df <- data.frame(a= c(FALSE, NA, TRUE, TRUE),
b= c(TRUE, FALSE, FALSE, NA),
c= c(TRUE, TRUE, NA, NA))
df
# a b c
# 1 FALSE TRUE TRUE
# 2 NA FALSE TRUE
# 3 TRUE FALSE NA
# 4 TRUE NA NA
expected <- c("b", "c", "c", "a", "a")
从第一行转到最后一行,在第一行中看到true
。这是多个true
s,因此我们从左到右转,然后获得“ b”
和“ c”
。在第二个拖车中,我们得到“ C”
,依此类推。
如何(以一种优雅的方式)做到这一点?
I have a named dataframe containig logicals with missings and I want to get a vector with the column names where values are TRUE
(going down the rows and, if multiple TRUE
s in one row, going from left to right). Here an example:
df <- data.frame(a= c(FALSE, NA, TRUE, TRUE),
b= c(TRUE, FALSE, FALSE, NA),
c= c(TRUE, TRUE, NA, NA))
df
# a b c
# 1 FALSE TRUE TRUE
# 2 NA FALSE TRUE
# 3 TRUE FALSE NA
# 4 TRUE NA NA
expected <- c("b", "c", "c", "a", "a")
Going from first to last row we see TRUE
in the first row. Here are multiple TRUE
s, thus we go from left to right and get "b"
and "c"
. In second tow we get "c"
, and so on.
How to do this (in an elegant way)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在
基本
r:You can do in
base
R:您也可以尝试使用
应用
You can also try using
apply
continue
Here is a tidyverse way:
Or:
基于
purrr :: pmap
的另一个可能的解决方案:Another possible solution, based on
purrr::pmap
:您可以使用
%%
(modulo)来标识列索引。基准
You can use
%%
(modulo) to identify the column indices.Benchmark