mercredi 11 novembre 2020

Creating a new variable under conditions of other variables in R

I have a function that match blood type for donors and recipient (Recipient A ---> Donor A or O; Recipient B ---> Donor B or O; Recipient O ---> donor O; Recipient AB ---> donor A, B, O or AB). i used cbind function. But i keep getting a warning message even though i got the desired output (this has been resolved by @hachiko and i no longer see the warning message). I was wondering how can i add a character vector with blood type frequencies within the function.

1- Here is my data

######################
#  Sample data       #
######################
# sample data for recipients

IDr= c(seq(1,5))
BTR=c("A","B","AB","O","O")
data_R=data.frame(IDr,BTR,A=c(0,1,rep(0,3)),B=c(0,rep(0,3),1),C=c(0,rep(1,3),0),D=c(0,rep(1,4)),E=c(1,1,0,rep(1,1),0),stringsAsFactors=FALSE)

data_R
  IDr BTR A B C D E
1   1   A 0 0 0 0 1
2   2   B 1 0 1 1 1
3   3  AB 0 0 1 1 0
4   4   O 0 0 1 1 1
5   5   O 0 1 0 1 0

# sample data for donors

IDd= c(seq(1,8))
BTD= c("A","B","AB","O","AB","AB","O","O")
fg= c(rep(0.0025, each=2),rep(0.00125, each=2),rep(0.0011, each=2),rep(0.0015, each=2))
data_D=data.frame(IDd,BTD,A=c(rep(0,5),1,1,1),B=c(rep(0,6),1,1),C=c(rep(1,7),0),D=rep(1,8),E=c(rep(0,5),rep(1,2),0),fg,stringsAsFactors=FALSE)

# i ordered my data_D
data_D
  IDd BTD A B C D E      fg
2   2   A 0 0 1 1 0 0.00250
4   4  AB 0 0 1 1 0 0.00125
5   5   B 0 0 1 1 0 0.00110
6   6   O 0 0 1 1 0 0.00110
7   7  AB 0 0 1 1 0 0.00150
8   8  AB 1 0 1 1 1 0.00150
1   1   O 1 1 0 1 0 0.00250
3   3   O 1 1 1 1 1 0.00125

2- Here is my function that match blood types

# my function
  ftest=function(i){
    if(data_R[i,2]=="A"){
      tab=as.data.frame(cbind(data_R[i,1:2],data_D[which((data_D[2]=="A") | (data_D[2]=="O")),][,1:2],row.names = NULL))
    }else if(data_R[i,2]=="B"){
      tab=as.data.frame(cbind(data_R[i,1:2],data_D[which((data_D[2]=="B") | (data_D[2]=="O")),][,1:2],row.names = NULL))
    }else if(data_R[i,2]=="O"){
      tab=as.data.frame(cbind(data_R[i,1:2],data_D[which (data_D[2]=="O"),][,1:2],row.names = NULL))
    }else{
      tab=as.data.frame(cbind(data_R[i,1:2],data_D[,1:2],row.names = NULL))
    }
   return(tab)
  }

# current output
 ftest(1)
  IDr BTR IDd BTD
1   1   A   2   A
2   1   A   6   O
3   1   A   1   O
4   1   A   3   O

3- i want to add the vector ABO_freq within my ftest function i can not add directly to my data_D.

#  vector to be added within function
ABO_freq=c(0.03,0.42,0.09,0.46)
names(ABO_freq)=c("AB","A","B","O")

so the desired output for my ftest function would be, for example ,for first patient data_R[1,]

# desired output
  IDr BTR IDd BTD ABO_freq
1   1   A   2   A  0.42
2   1   A   6   O  0.46
3   1   A   1   O  0.46
4   1   A   3   O  0.46

Thank you in advance for any help or advise.

Aucun commentaire:

Enregistrer un commentaire