Dataframe create new column based on other columns

One option is ifelse which is vectorized version of if/else. If we are doing this for each row, the if/else as showed in the OP’s pandas post can be done in either a for loop or lapply/sapply, but that would be inefficient in R.

df <- transform(df, c= ifelse(a==b, a+b, b-a))
df
#  a  b  c
#1 1  1  2
#2 2 20 18
#3 3  3  6
#4 4  4  8
#5 5 50 45

This can be otherwise written as

df$c <- with(df, ifelse(a==b, a+b, b-a))

to create the ‘c’ column in the original dataset


As the OP wants a similar option in R using if/else

df$c <- apply(df, 1, FUN = function(x) if(x[1]==x[2]) x[1]+x[2] else x[2]-x[1])

Leave a Comment