convert factor with 11 levels to character or numeric
I have the following data frame (imported from a csv) with a row of factors with 11 levels.
> df_ave[1,]
ExtCal.Average ExtCal.Average.1 ExtCal.Average.2 ExtCal.Average.3 ExtCal.Average.4 ExtCal.Average.5
Isotope 7Li 11B 31P 63Cu 66Zn 85Rb
ExtCal.Average.6 ExtCal.Average.7 ExtCal.Average.8 ExtCal.Average.9 ExtCal.Average.10 ExtCal.Average.11
Isotope 88Sr 90Zr 137Ba 139La 140Ce 141Pr
ExtCal.Average.12 ExtCal.Average.13 ExtCal.Average.14 ExtCal.Average.15 ExtCal.Average.16
Isotope 146Nd 147Sm 153Eu 157Gd 172Yb
ExtCal.Average.17 ExtCal.Average.18 ExtCal.Average.19 ExtCal.Average.20
Isotope 178Hf 208Pb 232Th 238U
I want to convert that row to characters (so I can then use it to replace the column names with it), but if I do as.character(df_ave[1,])
, I get:
[1] "10" "6" "5" "10" "10" "10" "10" "10" "7" "7" "6" "6" "7" "6" "7" "6" "7" "6" "8" "6" "6"
Not what I expected!! What do I do wrong??
Same thing for the 2nd row, it's a factor with 11 levels that I want to convert to numeric (without 2 digits after the decimal point, not integer):
> df_ave[2,]
ExtCal.Average ExtCal.Average.1 ExtCal.Average.2 ExtCal.Average.3 ExtCal.Average.4
3622 406.69367683495113 125.40906252040027 93581.601747523237 3003.005804863546 19973.538736364932
ExtCal.Average.5 ExtCal.Average.6 ExtCal.Average.7 ExtCal.Average.8 ExtCal.Average.9
3622 3.9733143041662951 103289.61846650975 89140.8626528866 104283.72610637423 13235.807622402481
ExtCal.Average.10 ExtCal.Average.11 ExtCal.Average.12 ExtCal.Average.13 ExtCal.Average.14
3622 27535.452396889865 3566.5632181365959 14399.937899081722 3284.1060413886876 1069.0985077873447
ExtCal.Average.15 ExtCal.Average.16 ExtCal.Average.17 ExtCal.Average.18 ExtCal.Average.19
3622 3555.409906877464 1657.8443498763834 2314.1788460028692 2057.1117900629424 3011.643780160347
ExtCal.Average.20
3622 552.89402766758417
I tried: > as.numeric(paste(df_ave[2,]))
but get:
[1] 7 7 10 7 6 7 4 9 5 6 7 7 6 7 5 7 6 7 7 7 9
Clearly not the expected level. I get the same result if I enter > as.numeric(df_ave[2,])
. I guess it's returning the factor level, not the value itself?? Any help appreciated. These factors are driving me nuts.
有很多方法,但我能找到的最直接的方法是使用as.matrix首先转换为字符:
df <- data.frame(a=factor(1), b=factor(2), c=factor(3))
as.numeric(as.matrix(df)[1,])
链接地址: http://www.djcxy.com/p/24954.html
上一篇: 如何在Native android应用程序中使用WebRTC + Pubnub Api进行视频聊天客户端
下一篇: 将11个级别的因子转换为字符或数字