删除数据框中包含常用字符名称的列

问题描述 投票:0回答:3

我在 r 中有一个数据框,其中包含多个名称中具有相似字符的列,例如:

  tom_wa = c(1,1,1);
  tom_ba = c(2,2,2);
  jim_wa = c(3,3,3);
  jim_ba = c(4,4,4);
  df <- data.frame(tom_wa, tom_ba, jim_wa, jim_ba)

实际数据框有超过30列,有没有一种简洁的方法可以过滤掉仅包含“_ba”或“_wa”的列?

r dataframe dplyr tidy
3个回答
1
投票
library(dplyr)
df %>% 
  select(ends_with(c("ba", "wa")))

0
投票

使用base R,你可以这样做:

df[grep("_(b|w)a", names(df))]  

0
投票

您可以使用 dplyr 中的

select
matches
函数,如下所示:

df %>% 
  select(matches("_ba"))
© www.soinside.com 2019 - 2024. All rights reserved.