简体   繁体   English

R语言中数据框列值转换问题

[英]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.作为 R 的新手,我正在尝试将列的值转换为数据框中的数字。

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: R 常见问题解答指出:

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.在将数值数据读入 R 时(通常在读入文件时),它们可能会作为因素出现。 If f is such a factor object, you can use如果 f 是这样一个因素 object,您可以使用

as.numeric(as.character(f)) to get the numbers back. as.numeric(as.character(f)) 来取回数字。 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). as.numeric(levels(f))[as.integer(f)] 在任何情况下,不要为手头的任务直接调用 as.numeric() 或他们的喜欢(as.numeric() 或 unclass() 给内部代码)。

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.您也可以在R常见问题解答中查看原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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