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