Reputation: 474
I am trying to create a for loop that subsets a data frame. Here is the data:
df1 <- data.frame(
Number = c(45,62,27,34,37,55,40),
Day = c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"),
Time = c("1pm", "4pm", "3pm", "2pm", "4pm", "1pm", "2pm"),
City = c("Chicago", "New York", "LA", "Miami", "San Diego", "Austin", "Dallas"))
The function I am trying is:
allNames<-variable.names(df1)
for (i in allNames){
if(any(variable.names(df1)== i)){
i <- df1[,c(i)]
}
}
Basically I am trying to subset the data file so the end result would be 4 data sets each with one variable from df1 and each subsetted data set would be named the variable that it represents. It would look like this for each variable from df1
Number
1 45
2 62
3 27
4 34
5 37
6 55
7 40
Day
1 Mon
2 Tues
3 Wed
4 Thurs
5 Fri
6 Sat
7 Sun
Thanks!
Upvotes: 0
Views: 882
Reputation: 521
Try:
for (i in allNames) {
if(any(variable.names(df1)== i)) {assign(i, df1[,c(i)])}
}
Upvotes: 1