Reputation: 77
my data frame "test" looks like this:
Date 1 2 3
01.01.1985 NA NA NA
09.01.1985 NA NA NA
17.01.1985 0.05173014 0.04578678 0.04326039
25.01.1985 NA NA NA
02.02.1985 NA NA NA
10.02.1985 0.05835957 0.05499137 0.05497832
For each column from 1 to n (except for the date column) I want to create 1 to n (in this example 3) dataframes that each contain the date column and another column from 1 to n. Example:
Date 3
1 01.01.1985 NA
2 09.01.1985 NA
3 17.01.1985 0.04326039
4 25.01.1985 NA
5 02.02.1985 NA
6 10.02.1985 0.05497832
Ideally each new dataframe would be named after its number "n" or something like "new_frame_n". As my whole data frame contains more than a thousand rows (dates) and something around 50 columns (named after 1 to n) i would like to figure out a way to do that automatically. I've tried it in numerous ways, this is what i have so far:
i <- 2 #start at second column
m <- ncol(test) # assign this to length of loop
m
for (i in 2:m) {
new_frame_[[i-1]] <- subset(test, select = c(Date, i))
i <- i+1
}
I've come across this How to create multiple data frames from a huge data frame using a loop? [closed], tried to apply it to my data but it didn't work, so i thought a loop would work. I'm pretty new to r. Thanks a lot!
Upvotes: 1
Views: 1275
Reputation: 1553
Try this:
df <- read.table(textConnection("
Date 1 2 3
01.01.1985 NA NA NA
09.01.1985 NA NA NA
17.01.1985 0.05173014 0.04578678 0.04326039
25.01.1985 NA NA NA
02.02.1985 NA NA NA
10.02.1985 0.05835957 0.05499137 0.05497832" ) ,header=TRUE)
for ( i in 1:ncol(df[-1])) {
assign(paste0("new_frame", i), cbind(df[1], df[-1][i]))
}
Upvotes: 2