[R] convert factor data to numeric

jim holtman jholtman at gmail.com
Fri Oct 15 04:51:23 CEST 2010


If you read the data as posted in your email with read.csv, you
probably got this:

> s1 <- read.csv(textConnection("treat   absorb
+ 0          1.8052
+ 0.5       2.07075
+ 1.0       2.2345"))
> closeAllConnections()
> s1
     treat...absorb
1 0          1.8052
2 0.5       2.07075
3  1.0       2.2345
> str(s1)
'data.frame':   3 obs. of  1 variable:
 $ treat...absorb: Factor w/ 3 levels "0          1.8052",..: 1 2 3
>

Do an str(s1) on your object to see what it say.  You data did not
have a comma as a separator and your:

> sapply(s1, class)
treat.absorb
   "factor"

did show a funny column name (treat.absorb), so check your data and
post back what the str said about it.  What you probably wanted to do
with the data is the following:

> s1 <- read.table(textConnection("treat   absorb
+ 0          1.8052
+ 0.5       2.07075
+ 1.0       2.2345"), header = TRUE)
> closeAllConnections()
> str(s1)
'data.frame':   3 obs. of  2 variables:
 $ treat : num  0 0.5 1
 $ absorb: num  1.81 2.07 2.23
> s1
  treat  absorb
1   0.0 1.80520
2   0.5 2.07075
3   1.0 2.23450
>

now you probably have the right structure to process.

On Thu, Oct 14, 2010 at 9:53 PM, andreas <andreasseger at web.de> wrote:
>
> I have yet another novice 'converting factors to numeric problem'.
>
> The problem is as described by others: read data (using read.csv) in from
> excel.csv file and it turns out to be a factor in R. The data in execl only
> has 4 rows:
>
> treat   absorb
> 0          1.8052
> 0.5       2.07075
> 1.0       2.2345
>
> I read the object in as s1 and generated the following r-code and output
> trying a couple of things:
>
>
>
> as.numeric(as.character(s1))
> [1] NA
> Warning:
>> sapply(s1, class)
> treat.absorb
>    "factor"
>
>> as.numeric(as.character(s1))
> [1] NA
> Warining:
> NAs produced by conversion
>
>> as.numeric(as.character(s1$absorb))
> numeric(0)
>
>> s1$absorb <- as.numeric(as.character(s1$absorb))
> Error in `$<-.data.frame`(`*tmp*`, "absorb", value = numeric(0)) :
>  replacement has 0 rows, data has 3
>
> thanks for your consideration
>
> Andreas
> --
> View this message in context: http://r.789695.n4.nabble.com/convert-factor-data-to-numeric-tp1012855p2996406.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list