use filter_at in dplyr to filter all the columns excpet two or three columns

I wanted to select all the columns (col2,col3,col4,col5,col6) excpet (col1,col2) that equal to 2

the first image shows the raw data
Capture

the second image show what I wanted to do

Capture1

and I have used dplyr package for this purpose but it did not work
could you please help me to fix this problem

here you can find the r code:

library(dplyr)
df<- read.csv("temp.csv")
df2<- df %>% filter_at(vars(names(df[,c(2:5)])),all_vars(.==2))

I got the following result:
Capture2

Your picture shows columns 3 to 6, but your code 2 to 5 ?

1 Like

Brute force method:


df1  <- tibble::tribble(
          ~col1, ~col2, ~col3,
            11L,   11L,   11L,
             5L,    2L,    2L
          )


df1  %>%  filter( col2 == 2 & col3 == 2)

1 Like

Adjusting the columns being filtered will provide your intended result.

library(tidyverse)

df = data.frame(
  col1 = c(11, 16, 14, 2, 34, 12, 2),
  col2 = c(11, 5, 14, 2, 2, 4, 66),
  col3 = c(3, 5, 2, 2, 8, 2, 2),
  col4 = c(7, 10, 2, 11, 2, 20, 2),
  col5 = c(11, 11, 23, 2, 2, 2, 2),
  col6 = c(5, 4, 1, 2, 2, 2, 2)
)

df2<- df %>% filter_at(vars(names(df[,c(3:6)])),all_vars(.==2))

df2
#>   col1 col2 col3 col4 col5 col6
#> 1    2   66    2    2    2    2
1 Like

Thank you very much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.