Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.2k points)

From the below data frame, I want to apply the subset function():

df<-data.frame(

id=c(1:5),

ax1=c(5,3,7,-1,9),

bx1=c(0,1,-1,0,3),

cx1=c(2,1,5,-1,5),

dx1=c(3,7,2,1,8))

The data set has a variable x1 that is estimated at different time points, denoted by ax1, bx1, cx1, and dx1. I am trying to subset these data by eliminating the rows with -1 on any column like on ax1, bx1, cx1, and dx1. I would like to know if there is a way to automate filtering (or filter function) to perform this task. 

1 Answer

0 votes
by (107k points)

You can either achieve from the base R :

With rowSums:

cols <- grep('x1$', names(df))

df[rowSums(df[cols] == -1) == 0, ]

#  id ax1 bx1 cx1 dx1

#1  1   5   0   2   3

#2  2   3   1   1   7

#5  5   9   3   5   8

Or you can also use the apply method :

df[!apply(df[cols] == -1, 1, any), ]

If you are a beginner and want to know more about R then do check out the R programming tutorial.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...