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

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Thu Apr 19 20:35:03 CEST 2018


Hello,

When programming it is better to use dat[["variable"]] than dat$variable.

So your code could be

pfas.pheno[[cat.var]] <- NA
pfas.pheno[[cat.var]][pfas.pheno[,i] <= quantile(pfas.pheno[,i],0.25, 
na.rm =T)] <- 0

etc.

Untested.

Hope this helps,

Rui Barradas

On 4/19/2018 7:20 PM, Ding, Yuan Chun wrote:
> 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}}
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list