[R] how to change data type in data frame?

Liaw, Andy andy_liaw at merck.com
Mon Oct 4 22:16:32 CEST 2004


Here's one way:

> temp <- as.matrix(trash)
> temp[temp=='b'] <- 1
> temp[temp=='a'] <- 0
> temp <- as.data.frame(structure(as.numeric(temp), dim=dim(trash),
dimnames=dimnames(trash)))
> temp
  age typeI typeII
1   1     0      1
2   2     0      0
3   3     1      1
4   4     0      1
5   5     1      0

HTH,
Andy

> From: Auston_Wei at mdanderson.org
> 
> Hi, list,
> 
> suppose i have such a data frame:
> 
> trash <- 
> data.frame(cbind(seq(1:5),c('a','a','b','a','b'),c('b','a','b'
> ,'b','a')))
> names(trash) <- c('age','typeI','typeII')
> 
> and I want to change all 'a's to be 0 and 'b's to be 1. 
> 
> temp <- as.matrix(trash)
> temp[temp=='a'] <- 0
> temp[temp=='b'] <- 1
> temp <- data.frame(temp)
> 
> the problem was that temp$typeI and temp$typeII were still factors, 
> whereas I want numeric type. How can I make it?
> 
> Thanks,
> Auston
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list