0

I am just trying to convert a column of numbers, which R thinks are characters, to numerical values.

I have the following table:

> longtab=as.data.frame(table(long));head(longtab)
    long Freq
1 189485    1
2 189486    1
3 189487    1
4 189488    1
5 189489    1
6 189490    1

I've created a new table from those data as follows:

> q=head(longtab);q
    long Freq
1 189485    1
2 189486    1
3 189487    1
4 189488    1
5 189489    1
6 189490    1

When I test whether the "long" column is numeric, R tells me that it is not.

> is.numeric(q$long)
[1] FALSE

When I try to coerce "long" values to be numeric using as.numeric(), I get the following:

> as.numeric(q$long)
[1] 1 2 3 4 5 6

But these are the row numbers not the values in the "long" column. This seems like it should be a simple problem to fix but I am struggling and have been at this a while. Any help would be greatly appreciated.

Digsby
  • 151
  • 10
  • 4
    This will give what you want `as.numeric(as.character(q$long))`. – OceanSky_U Feb 20 '21 at 00:31
  • 1
    @Digsby: I believe that OceanSky_U is probably correct. Your "long" column was a factor (as evidenced by the result of coercing to to numeric class.) Factors often print in a a manner that makes then appear to be numbers. Commonly this occurred when Excel spreadsheets were imported with read.* functions, because any notes end up coercing the result to factor. It's probably a bit less common in the most recent version of R. You might only need `as.numeric` now that the default for the read.table parameter, stringsAsFactors, has been changed to FALSE. – IRTFM Feb 20 '21 at 00:56
  • `table()` will always turn the values you are counting into factors. It doesn't expect to work with numeric values. A base R solution that would work is: `y<-aggregate(long, list(value = long), length)` which skips the `table()` step altogether. – MrFlick Feb 20 '21 at 03:31

0 Answers0