Search code examples
rloopsfor-loopformula

R: How to make a for loop that performs a formula over a few columns (variables) in a new variable


Is it possible to make a for loop in a data frame that produces an outcome value for every row stored in a new variable/column (i.e., 3 columns (variables) X, Y, and Z. that produces value A for every row depending on values of the same row in those variables).

enter image description here

For example I want to do 0.5X * 1.2Y + 0.75Z and put the value in a new column and then loop the same formula for all the rows

Thanks in advance!


Solution

  • A dplyr option:

    library(dplyr)
    df %>%
      mutate(new = 0.5*X*1.2*Y+0.75*Z)
    

    Output:

      X Y Z  new
    1 1 3 5 5.55
    2 4 2 2 6.30
    3 2 5 1 6.75
    

    Data

    df <- data.frame(X = c(1,4,2),
                     Y = c(3,2,5),
                     Z = c(5,2,1))