Delete column and next column based on text

Viewed 35

I have a data like this :

enter image description here

and I want to delete the column which contain "rico" and also delete all next columns. I am looking to get this : enter image description here

This is what i did but it doesnt work :

mydata = data.frame(
  X1 = c("john", "max", "jay", "douglas"),
  X2 = c("alexia", "miguel", "vince", "gary"),
  X3 = c("peter", "rico", "joe", "jenny"),
  X4 = c("marc", "kelly", "max", "jones")
)

mydata[,grepl("rico", names(mydata))]

Some help would be appreciated

2 Answers

You can subset mydata with a range ending one before where grepl hits rico.

mydata[1:(grep("rico", mydata)-1)]
#mydata[1:(grep("rico", mydata)[1]-1)] #Alternative when there are more hists
#       X1     X2
#1    john alexia
#2     max miguel
#3     jay  vince
#4 douglas   gary

You can use colSums -

mydata[cumsum(colSums(mydata == 'rico') > 0) == 0]

#       X1     X2
#1    john alexia
#2     max miguel
#3     jay  vince
#4 douglas   gary

Using colSums we count number of times 'rico' is present in each column, we create a logical vector by comparing it with > 0, using cumsum we select all the columns before the 1st occurrence of the word.

Related