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

Yuan Chun Ding ycd|ng @end|ng |rom coh@org
Tue Apr 7 20:34:37 CEST 2020


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 Ravg variable should be  same as  m3 variable in the following small example.

my R code did not generate errors but not generate a new variable.

Ravg <- "rare_allele"
  tem2 <-data.frame(m1=c(12, 23, 22, 23), m2=c(23, 23, 3, 5), m3 =c(12, 23, 12.5, 5))
  for (r in 1:nrow(tem2)) { 
  if (tem2$m1[r] ==23 & tem2$m2[r] ==23) {
    tem2[[Ravg]][r] ==23} else if(tem2$m1[r] ==23 & tem2$m2[r] !=23){
    tem2[[Ravg]][r] ==tem2$m2[r]} else if (tem2$m1[r] !=23 & tem2$m2[r] ==23) {
    tem2[[Ravg]][r] ==tem2$m1[r]} else {
    tem2[[Ravg]][r] == mean(tem2$m1[r] + tem2$m2[r])}
                          }

Thank you,

Ding

----------------------------------------------------------------------
------------------------------------------------------------
-SECURITY/CONFIDENTIALITY WARNING-  

This message and any attachments are intended solely for the individual or entity to which they are addressed. This communication may contain information that is privileged, confidential, or exempt from disclosure under applicable law (e.g., personal health information, research data, financial information). Because this e-mail has been sent without encryption, individuals other than the intended recipient may be able to view the information, forward it to others or tamper with the information without the knowledge or consent of the sender. If you are not the intended recipient, or the employee or person responsible for delivering the message to the intended recipient, any dissemination, distribution or copying of the communication is strictly prohibited. If you received the communication in error, please notify the sender immediately by replying to this message and deleting the message and any accompanying files from your system. If, due to the security risks, you do not wish to receive further communications via e-mail, please reply to this message and inform the sender that you do not wish to receive further e-mail from the sender. (LCP301)



More information about the R-help mailing list