Home > database >  How to combine R loop result in a dataframe
How to combine R loop result in a dataframe

Time:02-05

My current code is like below:

for (i in c(1:10)) 
{excess_returns <- i - 2
print(excess_returns
}

When I use print(), it prints out each output but how could I merge each output and make them into a data frame.

This is a simplified vision of my question, I got like 23 columns in a dataset and I would like to use each one of each to subtract another one column, and combine all the outputs together to form up a new dataframe

Thanks for helping

CodePudding user response:

To return the output of the loop as a data.frame, we can use @DaveArmstrong's answer. But we can also use a looping function to achieve the same desired output:

lapply(1:10, function(x) x - 2)

If we have an actual data.frame, we use the dataframe as argument to lapply, as in:

my_df <- iris[1:4]

lapply(my_df, \(x) x-2)

Or with dplyr:

library(dplyr)

my_df %>% mutate(across(everything(), ~ .x -2))

CodePudding user response:

How about like this:

excess_returns <- rep(NA, 10)
for (i in c(1:10)) {
  excess_returns[i] <- i - 2
}
excess_returns
#>  [1] -1  0  1  2  3  4  5  6  7  8

Created on 2022-02-04 by the reprex package (v2.0.1)

Note that in the above, you first initialize the excess_returns vector and then fill it in with the for loop. This is the preferred method, particularly if the real data problem is much larger than this toy example.

  •  Tags:  
  • Related