使用ends_with在R中动态选择列 [英] Select columns dynamically in R with ends_with

查看:120
本文介绍了使用ends_with在R中动态选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想通过选择所有实例来减小其大小。TRUE出现在数据框中。

I have a dataframe where I want to reduce its size by selected all instances TRUE appears in dataframe.

以下是数据框:

df<-structure(c("1", "2", "3", "4", "5", "TRUE", "FALSE", "TRUE", 
"TRUE", "FALSE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", 
"TRUE", "FALSE", "FALSE", "TRUE", "FALSE", "a", "b", "c", "d", 
"e"), .Dim = c(5L, 5L), .Dimnames = list(NULL, c("A", "B_down", 
"C_down", "D_down", "E")))

为了将数据框缩小为TRUE,我使用了代码:

To reduce the dataframe to where TRUE is, I used this code:

df[which(apply(df[,c(2:4)],1,function(x) any(x)=="TRUE")),]

但是,我手动选择了列c(2 :4)- B_down C_down D_down ,因为它们以 _down 结尾。我如何在R中动态选择这些列,而无需对其进行硬编码。

However, I manually selected columns c(2:4) - B_down, C_down, D_down, as they have _down ending. How do I choose these columns dynamically in R, without hard coding it.

我在[此处发布](使用dplyr在多列上对多个条件进行过滤),则可以使用 select(df,ends_with( _ down)),但这只给了我一部分数据帧。我希望像上面那样维护整个数据框结构。

I see in a [post here] (filtering with multiple conditions on many columns using dplyr), one can use select(df, ends_with("_down")), but this only gives me a partial dataframe. I want the whole dataframe structure to be maintained as above.

谢谢您的帮助。

推荐答案

有更好的方法来处理您的数据,但继续您的示例中的工作流程将奏效。

There are better ways to handle your data but continuing the workflow from your example this would work.

df[apply(df[, endsWith(colnames(df), "_down")], 1, function(x) any(x == "TRUE")), ]

#      A   B_down C_down  D_down  E  
#[1,] "1" "TRUE" "FALSE" "TRUE"  "a"
#[2,] "3" "TRUE" "FALSE" "FALSE" "c"
#[3,] "4" "TRUE" "TRUE"  "TRUE"  "d"






另一种方法是


Another approach would be

df[rowSums(df[, endsWith(colnames(df), "_down")] == "TRUE") > 0, ]

#      A   B_down C_down  D_down  E  
#[1,] "1" "TRUE" "FALSE" "TRUE"  "a"
#[2,] "3" "TRUE" "FALSE" "FALSE" "c"
#[3,] "4" "TRUE" "TRUE"  "TRUE"  "d"

这篇关于使用ends_with在R中动态选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆