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

Ding, Yuan Chun
2018-04-19T18:20:37Z

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}}