用Grep和Piping删除列

Gre*_*ima 2 r

使用示例数据:

d1<-data.frame(years=c("1","5","10"),group.x=c(1:3),group.b=c(1:3),group.2x=c(1:3))
Run Code Online (Sandbox Code Playgroud)

我使用以下方法删除了列:

d2<-d1[,-grep("\\.x$",colnames(d1))]
Run Code Online (Sandbox Code Playgroud)

是否有类似的方法来完成相同的使用管道?

d2<- d1 %>%
        filter(!grep("\\.x$",colnames()))
Run Code Online (Sandbox Code Playgroud)

收益: Error: argument "x" is missing, with no default

目标是删除以.结尾的列 ".x"

tal*_*lat 8

在dplyr中,filter将删除行并select用于删除/选择您想要的列.您可以坚持使用,grep但dplyr还提供了一些特殊功能,例如ends_with:

library(dplyr)
d1 %>% 
  select(-ends_with(".x"))
#  years group.b group.2x
#1     1       1        1
#2     5       2        2
#3    10       3        3
Run Code Online (Sandbox Code Playgroud)

看看help("select")有关您可以在其中使用的其他"特殊功能"的更多信息dplyr::select.