1. Using the transform()
and ifelse()
functions of the base R:
df <- data.frame(col_1 = c(1, 3, 5, 7), col_2 = c(8, 6, 4, 2))
print(df)
# Adding the column col_3 to the data frame df
df <- transform(df, col_3 = ifelse(col_1 < col_2, col_1 + col_2, col_1 * col_2))
print(df)
Powered By
Output:
col_1 col_2
1 1 8
2 3 6
3 5 4
4 7 2
col_1 col_2 col_3
1 1 8 9
2 3 6 9
3 5 4 20
4 7 2 14
Powered By
2. Using the with()
and ifelse()
functions of the base R:
df <- data.frame(col_1 = c(1, 3, 5, 7), col_2 = c(8, 6, 4, 2))
print(df)
# Adding the column col_3 to the data frame df
df["col_3"] <- with(df, ifelse(col_1 < col_2, col_1 + col_2, col_1 * col_2))
print(df)
Powered By
Output:
col_1 col_2
1 1 8
2 3 6
3 5 4
4 7 2
col_1 col_2 col_3
1 1 8 9
2 3 6 9
3 5 4 20
4 7 2 14
Powered By
3. Using the apply()
function of the base R:
df <- data.frame(col_1 = c(1, 3, 5, 7), col_2 = c(8, 6, 4, 2))
print(df)
# Adding the column col_3 to the data frame df
df["col_3"] <- apply(df, 1, FUN = function(x) if(x[1] < x[2]) x[1] + x[2] else x[1] * x[2])
print(df)
Powered By
Output:
col_1 col_2
1 1 8
2 3 6
3 5 4
4 7 2
col_1 col_2 col_3
1 1 8 9
2 3 6 9
3 5 4 20
4 7 2 14
Powered By
4. Using the mutate()
function of the dplyr package and the ifelse()
function of the base R:
df <- data.frame(col_1 = c(1, 3, 5, 7), col_2 = c(8, 6, 4, 2))
print(df)
# Adding the column col_3 to the data frame df
df <- mutate(df, col_3 = ifelse(col_1 < col_2, col_1 + col_2, col_1 * col_2))
print(df)
Powered By
Output:
col_1 col_2
1 1 8
2 3 6
3 5 4
4 7 2
col_1 col_2 col_3
1 1 8 9
2 3 6 9
3 5 4 20
4 7 2 14
Leave a Reply