Skip to content
Prev 170948 / 398503 Next

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

The culprit is the cbind function.  When given 2 vectors (not already something else), cbind will create a matrix, not a data frame.  A matrix can only have 1 type, so the numbers get converted to character.  In your first example you never do create a data frame, you just build a matrix (try str(results)) so fix cannot change a single column to numeric in something that is a matrix.  In the second example you do create a data frame so fix will allow changing of columns, but the cbind inside the call to data.frame is still creating a matrix (and converting numeric to character) before it is included in the data frame.  Remove the cbind and just do:

out1 <- data.frame(species=as.character(paste(s)),obsnum=obsnum)

and then out1 will be a data frame without ever converting the number obsnum to a character.

Hope this helps,