简体   繁体   中英

Problem in Converting column's value of data frame in R-language

As a newbie in R, I am trying convert a column's values into numeric in my data frame.

My Code:

hData <- read.csv("outcome-of-care-measures.csv")

temp <- subset(hData, hData$State == "LA")

as.numeric(temp$Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia)

when I paste this

(temp$Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia)

Code in console without conversion it returns:

 [1] 12.5 12.7 13.0 9.6  9.8  11.5 9.5  11.2 10.2 11.1 9.7  9.6  9.3  11.0 13.5 9.3  10.6 9.9  12.0
[20] 11.3 12.6 13.1 10.7 11.2 9.9  9.7  9.2  14.2 10.6 10.8 10.1 12.6 12.7 7.4  12.9 10.1 12.9 11.0
[39] 11.7 10.6 8.4  11.7 11.0 10.8 12.6

After conversion it returns:

[1]  26  28  31 118 120  16 117  13   3  12 119 118 115  11  36 115   7 121  21  14  27  32   8  13
[25] 121 119 114  43   7   9   2  27  28  97  30   2  30  11  18   7 106  18  11   9  27

Please help me what I am missing...?

Since your data is stored as factors, it is a little complicated to convert them into numeric. R FAQ states:

How do I convert factors to numeric?

It may happen that when reading numeric data into R (usually, when reading in a file), they come in as factors. If f is such a factor object, you can use

as.numeric(as.character(f)) to get the numbers back. More efficient, but harder to remember, is

as.numeric(levels(f))[as.integer(f)] In any case, do not call as.numeric() or their likes directly for the task at hand (as as.numeric() or unclass() give the internal codes).

You should try this and it will give you the same results:

as.numeric(levels(temp$Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia)) 
[temp$Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia]

you can check out the reason here at R FAQ as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM