0

I have a data frame in R:

   > tempT
       Var1 Freq
    1  10397 1168
    2  13487  965

I want to get the column beginning with 10397. However, for some reason, when I type:

as.numeric(unlist(tempT["Var1"]))

, it gives me

[1] 1 2

Anyone know why it's doing that? Or how I would go about getting the column I want?

  • Are the values saved as factors? – Onyambu Mar 05 '18 at 05:01
  • 1
    Because `tempT$Var1` is probably a `factor`, where each unique value is stored as an integer from `1:n`. Just `tempT[["Var1"]]` or `tempT[,"Var1"]` or even `tempT$Var1` will do it. – thelatemail Mar 05 '18 at 05:01
  • 1
    Also see this old popular R FAQ for how to convert a factor to numeric properly - https://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information – thelatemail Mar 05 '18 at 05:16
  • Presuming you got this data frame by calling `as.data.frame` on a table, specify `stringsAsFactors = FALSE`, and `as.numeric(tempT$Var1)` (or equivalent) will work as expected. – alistaire Mar 05 '18 at 05:35

1 Answers1

0

These are factors, and this is a common headache :) It could have happened by a variety of means, but here's an example with your numbers:

(tempT <- data.frame(Var1 = c("10397", "13487"), Freq = c("1168", "965")))
#   Var1 Freq
# 1 10397 1168
# 2 13487  965

Just pull the levels instead of the values

levels(tempT$Var1)
# [1] "10397" "13487"

or if you want them to be numeric:

as.numeric(levels(tempT$Var1)
# [1] 10397 13487
De Novo
  • 7,120
  • 1
  • 23
  • 39