2

Possible Duplicate:
How to convert a factor to an integer\numeric without a loss of information

I want to count (and later on plot the count of) the unique values of an array:

data = c(1,2,3,4,5,2.1,1,2,1,2,1,4,5,7,8,9,6,5,4,3,2,2,1)
uniCount = as.data.frame(table(data))
uniCount$cumsum = cumsum(uniCount$Freq)

str(uniCount)

plot (uniCount$data, uniCount$Freq)
plot (uniCount$data, uniCount$cumsum)

But, the values of the column data is not 'numeric' but 'Factor'. For me it seems that the datatype Factor is an associative array of Strings. When I use as.numeric(uniCount$data) the result gives "1 2 3 4 5 6 7 8 9 10"

How can I convert the datatype "Factor" to the datatype "numeric"? Or how can I prevent that R converts my numeric values to a Facotr?

Community
  • 1
  • 1
R_User
  • 10,682
  • 25
  • 79
  • 120

2 Answers2

3

this may work for you

as.numeric(attr(uniCount$data,"levels"))

or

as.numeric(levels(uniCount$data))

if you dont want factors try

data = c(1,2,3,4,5,2.1,1,2,1,2,1,4,5,7,8,9,6,5,4,3,2,2,1)
uniCount = as.data.frame(table(data),stringsAsFactors =F)
uniCount$cumsum = cumsum(uniCount$Freq)

EDIT:

thanks @Carl Witthoft, but ?factor says that as.numeric(levels(uniCount$data))[uniCount$data] is recommended and slightly more efficient than as.numeric(as.character(uniCount$data))"

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
shhhhimhuntingrabbits
  • 7,397
  • 2
  • 23
  • 23
  • 1
    Heed the words of The R-Inferno (and I believe it's in the R-FAQ as well): always convert using `as.numeric(as.character(levels(blah)))` or you may not get what you expect. – Carl Witthoft Jun 18 '12 at 11:13
  • I feel it also should be mentioned that this is explicitly explained in the documentation of `?factor` as well. – Justin Jun 18 '12 at 21:14
0

The plyr package can make it easier to do such operations without getting character/factor variables.

library(plyr)
d <- data.frame(x=c(1,2,3,4,5,2.1,1,2,1,2,1,4,5,7,8,9,6,5,4,3,2,2,1))
ddply(d, "x", summarize, Freq=length(x))
Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142