如何通过保持原始列顺序的值过滤DataFrame列?



我试图过滤一个DataFrame,只保留包含"_time"或";___">

我尝试使用df %>% select(contains(c("_time", "___"))。但是,这会改变输出中列的顺序,首先显示所有带有_time的列,然后显示带有"___"的列。最后显示

如何在不改变列顺序的情况下进行过滤?

我们可以使用matches

library(dplyr)
df %>%
select(matches("_time|___"))

与产出

h_time l_time f___d m_time s___hello
1     11     16    21     26        31
2     12     17    22     27        32
3     13     18    23     28        33
4     14     19    24     29        34
5     15     20    25     30        35

相比
df %>%
select(contains(c("_time", "___")))
h_time l_time m_time f___d s___hello
1     11     16     26    21        31
2     12     17     27    22        32
3     13     18     28    23        33
4     14     19     29    24        34
5     15     20     30    25        35

数据
df <- data.frame(col1 = 1:5, col2 = 6:10, h_time = 11:15, 
l_time = 16:20, f___d = 21:25, m_time = 26:30, 
col_new = 41:45, s___hello = 31:35)

Base R:数据来自@akrun(非常感谢)

df[,grepl("_time|___", colnames(df))]
h_time l_time f___d m_time s___hello
1     11     16    21     26        31
2     12     17    22     27        32
3     13     18    23     28        33
4     14     19    24     29        34
5     15     20    25     30        35

最新更新