Q:

How to use sapply to apply function to vector_a[i] returning value from vector_b[i]

I want to apply a function to each value of dataframe$column1 returning a vector of the same length. The output should contain the value from dataframe$column2 (of the same row) if a condition apply. In (pseudo)code
function <- "If (value of dataframe$column1[i] is something) {return(dataframe$column1[i])} else {return(dataframe$column2[i])}  

output_vector <- sapply(dataframe$column1, function, dataframe$column2)

Does sapply remember the index of the vector when applying a function so to return a value from a different vector but with the same index?

A:

This is exactly what ifelse() does:
df = data.frame(col1=1:10, col2=21:30)
output_vector = ifelse(df$col1 > 5, df$col1, df$col2)

