r - Apply a different formula for each condition that is met in a certain data frame -
lets example have following data frame called "df1" (which part of larger data frame example now):
df1=
[,1] [,2] [,3] 1 -0.5 1.3 1 -0.3 0.9 5 -0.2 0.2 2 0.4 0.5 0 0.5 1.1 2 1.1 0.1 1 -0.6 1.8
and have created following conditions:
conda= df1[,2] >= 0 & df2[,3] > 1 condb= df1[,2] >= 0 & df2[,3] <= 1 condc= df1[,2] < 0 & df2[,3] > 1 condd= df1[,2] < 0 & df2[,3] <= 1
here comes question:
how apply different function each condition met in df1. example:
if conda met: df1[,1]=df1[,1]*1 if condb met: df1[,1]=df1[,1]*2 if condc met: df1[,1]=df1[,1]*3 if condd met: df1[,1]=df1[,1]*4
taking account example "df1", output data frame this:
[,1] [,2] [,3] 3 -0.5 1.3 # in row condc met 4 -0.3 0.9 # in row condd met 20 -0.2 0.2 # in row condd met 4 0.4 0.5 # in row condb met 0 0.5 1.1 # in row conda met 4 1.1 0.1 # in row condb met 3 -0.6 1.8 # in row condc met
help appreciated!!
just take wrote above , apply it.
conda <- df1[,2] >= 0 & df1[,3] > 1 df1[conda,1] <- df1[conda,1] * 1
(although, efficiencies sake skip 1 since doesn't anything. i'm assuming df2 in question typo since never mention otherwise.)
one way make briefer might make list out of conditions , cycle through.
conds <- list( conda= df1[,2] >= 0 & df1[,3] > 1, condb= df1[,2] >= 0 & df1[,3] <= 1, condc= df1[,2] < 0 & df1[,3] > 1, condd= df1[,2] < 0 & df1[,3] <= 1) for(i in 1:4) { df1[conds[[i]],1] <- df1[conds[[i]],1] * }
Comments
Post a Comment