Reputation: 57
I have a data set that contains a bunch of columns where the column values(all values of that column) is exactly the same as that column name. How can I delete that column. I cannot delete the columns one by one as there are over 700 variables. Thanks!
Upvotes: 0
Views: 493
Reputation: 1233
Does this help?
data = data.frame(name1=rep("name1",5), name2=rep("name2",5), name3=rep("name3",5), name4=rep("name4",5)) #Some test data
ColsToRemove <- names(data)[which(sapply(data[1,], function(x){x %in% names(data)}))] #Finds where the column name is the same as the first entry and marks it for deletion
cleanData = data[ , !(names(data) %in% ColsToRemove)] #This deletes the columns named
head(data)
head(cleanData)
Upvotes: 1
Reputation: 79208
You can use sweep
to determine all the values that are not equal to the colnames
data[colSums(sweep(data,2,colnames(data),"!="))>0]
Upvotes: 0
Reputation: 2216
Here is an example of how you could do it:
data = data.frame(x1 = rep(1,10), x2 = seq(1,20,by = 2),
x3 = rep("x3",10), x4 = 1:10, x5 = rep("x5",10))
col_rm = which(sapply(1:ncol(data), function(x) all(data[,x] == colnames(data)[x])))
data = data[,-col_rm]
basically what the code does it that finds if all the values of the column x
are equal to the name of the column and finds all the columns that fulfill that condition and then i just remove them with -
.
Upvotes: 3