[R] create multiple categorical variables in a data frame using a loop

Ding, Yuan Chun ycding @ending from coh@org
Thu Apr 19 20:20:37 CEST 2018


Hi All,

I want to create a categorical variable, cat.pfoa, in the file of pfas.pheno (a data frame) based on log2pfoa values. I can do it using the following code.

pfas.pheno <-within(pfas.pheno, {cat.pfoa<-NA
  cat.pfoa[pfas.pheno$log2pfoa <=quantile(pfas.pheno$log2pfoa,0.25, na.rm =T)]<-0
  cat.pfoa[pfas.pheno$log2pfoa >=quantile(pfas.pheno$log2pfoa,0.75, na.rm =T)]<-2
  cat.pfoa[pfas.pheno$log2pfoa >=quantile(pfas.pheno$log2pfoa,0.25, na.rm =T)
           &pfas.pheno$log2pfoa <=quantile(pfas.pheno$log2pfoa,0.75, na.rm =T)]<-1
  }

However, I have additional 7 similar variables, so I wrote the following code, but it does not work.

for (i in c("log2pfoa","log2pfos", "log2pfna", "log2pfdea",   "log2pfuda", "log2pfhxs", "log2et_pfosa_acoh", "log2me_pfosa_acoh"))  {
cat.var <- paste0("cat.",i)
pfas.pheno <- within(pfas.pheno, {eval(parse(text= cat.var))<-NA
eval(parse(text=cat.var))[pfas.pheno[,i] <= quantile(pfas.pheno[,i],0.25, na.rm =T)] <- 0
eval(parse(text=cat.var))[pfas.pheno[,i] >= quantile(pfas.pheno[,i],0.75, na.rm =T)] <- 2
eval(parse(text=cat.var))[pfas.pheno[,i] >= quantile(pfas.pheno[,i],0.25, na.rm =T)
                                  &pfas.pheno[,i] <= quantile(pfas.pheno[,i],0.75, na.rm =T)] < -1
})
                                                                                  }

Can you help me fix the problem?

Thank you,

Yuan Chun Ding
City of Hope National Medical Center



---------------------------------------------------------------------
-SECURITY/CONFIDENTIALITY WARNING-
This message (and any attachments) are intended solely f...{{dropped:22}}




More information about the R-help mailing list