Skip to content
Prev 170951 / 398503 Next

understanding how R determines numbers and characters when creating a data frame

Alan Smith wrote:
See ?cbind for a detailed explanation.
Anyway, when cbind/rbind is used on vector / matrix it returns matrix. 
Matrix are necessarily composed of the same type of data (see 
Introduction to R): combining character and numeric data you are 
implicitly converting the "short" type (numeric) to the "long" type 
(character).
Instead of using cbind here:
using data.frame:
out1 <- data.frame(species=as.character(paste(s)),obsnum)

you are telling R to convert character in factor and to preserve the 
numeric:
c(class(results$species),mode(results$species))
c(class(results$obsnum),mode(results$obsnum))

You can keep the character using the stringsAsFactors argument of the 
data.frame() function:
out1 <- data.frame(species=as.character(paste(s)),obsnum, 
stringsAsFactors=FALSE)

And then:
class(results$species)

The message is: if you want to mix up different data type you need lists 
(and data.frame are a special type of list where each component has the 
same number of elements).

Ciao,
domenico