Reputation: 103
I am novice in R. I want to write the loop for the below code in R.
day1<-XYZ[, -grep("_0", colnames(XYZ))]
day2<-XYZ[, -grep("_0|_1", colnames(XYZ))]
day3<-XYZ[, -grep("_0|_1|_2", colnames(XYZ))]
day4<-XYZ[, -grep("_0|_1|_2|_3", colnames(XYZ))]
day5<-XYZ[, -grep("_0|_1|_2|_3|_4", colnames(XYZ))]
day6<-XYZ[, -grep("_0|_1|_2|_3|_4|_5", colnames(XYZ))]
day7<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6", colnames(XYZ))]
day8<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7", colnames(XYZ))]
day9<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8", colnames(XYZ))]
day10<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8|_9", colnames(XYZ))]
day11<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8|_9|_10", colnames(XYZ))]
day12<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8|_9|_10|_11", colnames(XYZ))]
day13<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8|_9|_10|_11|_12", colnames(XYZ))]
day14<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8|_9|_10|_11|_12|_13", colnames(XYZ))]
day15<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8|_9|_10|_11|_12|_13|_14", colnames(XYZ))]
day16<-XYZ[, -grep("_0|_1|_2|_3|_4|_5|_6|_7|_8|_9|_10|_11|_12|_13|_14|_15", colnames(XYZ))]
Thanks in advance!!
Upvotes: 3
Views: 197
Reputation: 887048
We can use lapply
and create the subsets in a list
lst <- lapply(0:15, function(x) XYZ[, -grep(paste("_", 0:x, collapse="|",
sep=""), colnames(XYZ))])
names(lst) <- paste0("day", 1:16)
It is better not to create multiple objects in the global environments. But, if we it is for exploration
i1 <- 0:15
for(i in seq_along(i1)) {
assign(paste0("day", i),
value = XYZ[, -grep(paste("_", 0:i1[i], collapse="|", sep=""), colnames(XYZ))])
}
Upvotes: 3