ifelse package:base R Documentation _C_o_n_d_i_t_i_o_n_a_l _E_l_e_m_e_n_t _S_e_l_e_c_t_i_o_n _D_e_s_c_r_i_p_t_i_o_n: 'ifelse' returns a value with the same shape as 'test' which is filled with elements selected from either 'yes' or 'no' depending on whether the element of 'test' is 'TRUE' or 'FALSE'. _U_s_a_g_e: ifelse(test, yes, no) _A_r_g_u_m_e_n_t_s: test: an object which can be coerced to logical mode. yes: return values for true elements of 'test'. no: return values for false elements of 'test'. _D_e_t_a_i_l_s: If 'yes' or 'no' are too short, their elements are recycled. 'yes' will be evaluated if and only if any element of 'test' is true, and analogously for 'no'. Missing values in 'test' give missing values in the result. _V_a_l_u_e: A vector of the same length and attributes (including class) as 'test' and data values from the values of 'yes' or 'no'. The mode of the answer will be coerced from logical to accommodate first any values taken from 'yes' and then any values taken from 'no'. _W_a_r_n_i_n_g: The mode of the result may depend on the value of 'test', and the class attribute of the result is taken from 'test' and may be inappropriate for the values selected from 'yes' and 'no'. Sometimes it is better to use a construction such as '(tmp <- yes; tmp[!test] <- no[!test]; tmp)', possibly extended to handle missing values in 'test'. _R_e_f_e_r_e_n_c_e_s: Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) _The New S Language_. Wadsworth & Brooks/Cole. _S_e_e _A_l_s_o: 'if'. _E_x_a_m_p_l_e_s: x <- c(6:-4) sqrt(x)#- gives warning sqrt(ifelse(x >= 0, x, NA))# no warning ## Note: the following also gives the warning ! ifelse(x >= 0, sqrt(x), NA) ## example of different return modes: yes <- 1:3 no <- pi^(0:3) typeof(ifelse(NA, yes, no)) # logical typeof(ifelse(TRUE, yes, no)) # integer typeof(ifelse(FALSE, yes, no))# double