1

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

1
  • MGCons_FL2$PhiPS2 *0.55 * MGCons_FL2$Qin %o% seq(0.25, 0.75, 0.05) should give you all the columns you want Commented Aug 22, 2022 at 0:32

3 Answers 3

1

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

Comments

0
# 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

Comments

0
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)

Comments

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.