1

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!

2
  • I recommend using a list l <- lapply(seq_along(df)[-1], function(x) df[, c(1, x)]) if you must have them as separate objects, you can name the list elements, here I name them new_frame_1, _2, _3, and then do list2env(setNames(l, paste0('new_frame_', seq_along(l))), envir = .GlobalEnv) so that now you have three new data frame objects, new_frame_1, new_frame_2, new_frame_3, in your workspace Commented Mar 1, 2016 at 19:07
  • thanks for the advice. while looking for solutions i came across a lot of similar questions and basically the people who were answering always recommended to use a list. so i will try that as well. Commented Mar 3, 2016 at 8:37

1 Answer 1

2

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])) 
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.