[R] converting character to numeric

Sarah Goslee sarah.goslee at gmail.com
Tue Jun 21 22:52:22 CEST 2011


Hi Alina,

On Tue, Jun 21, 2011 at 4:38 PM, Alina Sheyman <alinashe at gmail.com> wrote:
> I'm trying to convert data from character to numeric.
>
>  I've imported data as a csv file, I'm assuming that the import is a
> database - are all the columns in  a database considered "vectors"  and that
> they can be  operated on individually
> Therefore I've tried the following
> mydata <- as.numeric(mydata$apples)

The term is data frame, not database. You don't tell us how you
imported the data - read.table()? read.csv()? Using what options?

You are right that each column can be operated on individually.

Are you certain that every element in mydata$apples is numeric? If it
were, read.table() wouldn't import it as character, but as numeric.

What does
str(mydata)
show?

> when i then look at mydata again  the named column is still in "character"
> format

How did you determine that?

>  if i do mydata2 <- as.numeric(mydata$apples)
> the new object mydata2 is empty.

This perplexes me; it means that R can't identify ANY of the
information in your column as numeric. If some were numeric and some
character, you would get a warning and the character values would be
replaced with NA.

> vec1 <- c("1", "2", "3")
> as.numeric(vec1)
[1] 1 2 3
> vec1 <- c("1", "2", "3", "a")
> as.numeric(vec1)
[1]  1  2  3 NA
Warning message:
NAs introduced by coercion


Are you certain that "apples" is the correct column name? R is case-sensitive.

> Am i missing something about the structure of R?
>

It's hard to tell. You are certainly missing a lot of the information
we need to answer your question.

Sarah

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list