2

I have a dataframe as below

string1  string2   var1  var2
  T        T        1     1    
  T        F        0     1
  F        F        0     0

I want to iterate through each row which has n number of rows and add conditions like below

 Iterate n number of rows
    if(string1 == T & sting2 == F){
      if(va1 > 1 & var2 > 1){
        # do some operation and append to new column
        # For example
        new column <- var1 + var2
       }
     elif(var1 == 0 & var2 > 1){
          # Do some adds / subs with var1 & var2 and append to new column
          }
     elif{var1 > 1 & var2 ==0){
          # Do some adds / subs with var1 & var2 and append to new column
     } 
    }
   elif(string1 == F & sting2 == T){
    # again repeat set of if-else opration on var1 and var2 as mentioned in 
       above if else condition
   }
   elif(nth condition)

How do i achieve in R

Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22

2 Answers2

2

Based on your description in comments I think you need is

df$new_col <- with(df, ifelse(string1 & string2 & var1 > 0 & var2 > 0, var1 + var2, 0))

df
#  string1 string2 var1 var2 new_col
#1    TRUE    TRUE    1    1       2
#2    TRUE   FALSE    0    1       0
#3   FALSE   FALSE    0    0       0

This adds up var1 and var2 if string1 and string2 is TRUE and both var1 and var2 are greater than 0 or else it keeps new_col as 0.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1
string1 <-c(T,T,F)
string2 <-c(T,F,F)
var1 <- c(1,0,0)
var2 <- c(1,1,0)
df <- data.frame(string1,string2,var1,var2)
df
  string1 string2 var1 var2
1    TRUE    TRUE    1    1
2    TRUE   FALSE    0    1
3   FALSE   FALSE    0    0
df$new_column <- apply(df, 1, function(x) ifelse(x[1] == T & x[2] == T & x[3] > 0 & x[4] > 0, x[1]+x[2], NA))
df
  string1 string2 var1 var2 new_column
1    TRUE    TRUE    1    1          2
2    TRUE   FALSE    0    1         NA
3   FALSE   FALSE    0    0         NA

Replace NA with 0, if you want to have 0 in the final result.

Adamm
  • 2,150
  • 22
  • 30
  • Thanks! But i have n number of conditions to validate, your solution holds good to validate one condition and update the nth column – user2277472 Mar 05 '19 at 13:22
  • You can modify `ifelse()` and put as many conds as you want (before the first comma). If you want some nested stuff I'll recommend to put another ifelse as first condition of previous one, or just run above command several times with different conditions. – Adamm Mar 06 '19 at 07:56