Re: [R] to create a new variable based on values in other variables

2020-04-07 Thread Yuan Chun Ding
Hi Bert, your code worked perfect. you always make me learn new R code skills! Thank you so much!! Ding From: Bert Gunter [bgunter.4...@gmail.com] Sent: Tuesday, April 7, 2020 12:53 PM To: Yuan Chun Ding Cc: r-help mailing list Subject: Re: [R] to

Re: [R] to create a new variable based on values in other variables

2020-04-07 Thread Bert Gunter
You can use subscripting to generalize and avoid multiply nested ifelse's which, I agree, can be a nightmare. However, you have to be very careful about the logic of the conditions you create and the order in which you apply them. It is very easy to wipe out an earlier relationship with a later

Re: [R] to create a new variable based on values in other variables

2020-04-07 Thread Yuan Chun Ding
Hi Thierry, the values in the example data frame are fake numbers, my original data frame has hundreds of row and values are in wide range, not min or max of two variables, also the number 23 is also different in different data frames. I agree I need to use vectorized ifelse, but I got

Re: [R] to create a new variable based on values in other variables

2020-04-07 Thread Thierry Onkelinx via R-help
Dear Ding, It seems that you are looking for the ifelse() function. Clear use of pmax() and pmin() reduces the number of if statements. m1 <- c(12, 23, 22, 23) m2 <- c(23, 23, 3, 5) Ravg <- ifelse( pmax(m1, m2) == 23, pmin(m1, m2), (m1 + m2) / 2 ) Best regards, ir. Thierry Onkelinx

[R] to create a new variable based on values in other variables

2020-04-07 Thread Yuan Chun Ding
Hi R users, I want to create a new variable, Ravg, in data frame tem2 based on values of two other variables m1 and m2. the condition: if m1 = 23 and m2 =23 then Ravg =23; else if m1 != 23 and m2=23 then Ravg =m1; else if m1 =23 and m2 !=23 then Ravg=m2; else Ravg=average of m1 and m2; the