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

StackOverflow https://stackoverflow.com/questions/18566581

  •  27-06-2022
  •  | 
  •  

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?

有帮助吗?

解决方案

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top