Home > OS >  How to loop in R to create multiple columns and populate with values
How to loop in R to create multiple columns and populate with values

Time:08-22

Hi I have a dataset and would like to make new columns and populate its rows by computations. I did something like this

# ETR = PhiPSII * 0.55 * Qin * fractionPSII
MGCons_FL2$ETR25 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.25
MGCons_FL2$ETR30 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.30
MGCons_FL2$ETR35 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.35
MGCons_FL2$ETR40 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.40
MGCons_FL2$ETR45 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.45
MGCons_FL2$ETR50 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.50
MGCons_FL2$ETR55 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.55
MGCons_FL2$ETR60 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.60
MGCons_FL2$ETR65 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.65
MGCons_FL2$ETR70 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.70
MGCons_FL2$ETR75 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.75

Can you help me use a loop function to automate this?

Thank you

CodePudding user response:

Consider sapply or vapply across a sequence of multiples of 5 and assign to block of columns:

mult5 <- seq(25, 75, by=5)

MGCons_FL2[paste0("ETR", mult5)] <- sapply(
    mult5, \(x) with(MGCons_FL2, PhiPS2 * 0.55 * Qin * (x/100))
)

MGCons_FL2[paste0("ETR", mult5)] <- vapply(
    mult5, \(x) with(MGCons_FL2, PhiPS2 * 0.55 * Qin * (x/100)),
    numeric(nrow(MGCons_FL2))
)

CodePudding user response:

# make a fake dataframe to test function
MGCons_FL2 <- tibble(PhiPS2 = rnorm(50),
                     Qin = rnorm(50))

# make a function that adds specified columns to the dataframe
column_maker <- function(col_name, number) {
  
  MGCons_FL2[ , col_name] <<- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*number
  
}

# map the function over you column names and the multiplier that changes with each column
map2(.x = c("ETR25", "ETR30", "ETR35", "ETR40"), .y = seq(from= .25, to = .4, by = .05), .f = column_maker)

# check the object, the columns have been put there
MGCons_FL2

CodePudding user response:

library(dplyr); library(tidyr)
MGCons_FL2 %>%
  crossing(fracPSII = seq(0.25, 0.75, by = 0.05)) %>%
  mutate(col = paste0("ETR", fracPSII * 100),
         val = PhiPS2*0.55   Qin*fracPSII) %>%
  select(-fracPSII) %>%
  pivot_wider(names_from = col, values_from = val)
  • Related