lundi 10 mai 2021

How to perform operations with condition within data frames in R?

I have a data frame made up of vectors that contains factors. I want to add another vector that contains calculation results conditioned to some of the factors:

W X Y Z
2 P1 15 if X = P1; Z = Y - W (Result Z = 13)
2 P2 15 if X = P2; Z = Y + W (Result Z = 17)

The attempts I have made have not been successful. Any tips?

w <- seq(2, 20, 2)
x <- c("P1", "P2")
y <- c(15, 30, 45, 60)
data <- expand.grid(W=w, X=x, Y=y)

z_values <- function(X){
if (X == "P1") {
  Y - W
} else {
  Y + W
}}

data$Z <- z_values(X)

Aucun commentaire:

Enregistrer un commentaire