Reputation: 91
I am using a for loop in order to remove every column of my data set where standard deviation = 0. I would like to do that with the apply function, do you have an idea?
sds<-apply(Dataset,2,sd, na.rm = FALSE)
counter=0
for(i in 1:length(sds)){
if(sds[i]==0){
Dataset<-Dataset[,-(i+5-counter)]
counter=counter+1
}
}
Upvotes: 1
Views: 74
Reputation: 887128
We can use Filter
Filter(sd, Dataset)
# col2 col3
#1 1 -0.545880758
#2 2 0.536585304
#3 3 0.419623149
#4 4 -0.583627199
#5 5 0.847460017
#6 6 0.266021979
#7 7 0.444585270
#8 8 -0.466495124
#9 9 -0.848370044
#10 10 0.002311942
sapply(Dataset, sd)
# col1 col2 col3
#0.0000000 3.0276504 0.5798524
Or use
Dataset[sapply(Dataset,sd)!=0]
set.seed(24)
Dataset <- data.frame(col1 = 1, col2 = 1:10, col3 = rnorm(10))
Upvotes: 1