当我将因子转换为数字或整数时,我得到基础级别代码,而不是值作为数字.
f <- factor(sample(runif(5), 20, replace = TRUE))
## [1] 0.0248644019011408 0.0248644019011408 0.179684827337041
## [4] 0.0284090070053935 0.363644931698218 0.363644931698218
## [7] 0.179684827337041 0.249704354675487 0.249704354675487
## [10] 0.0248644019011408 0.249704354675487 0.0284090070053935
## [13] 0.179684827337041 0.0248644019011408 0.179684827337041
## [16] 0.363644931698218 0.249704354675487 0.363644931698218
## [19] 0.179684827337041 0.0284090070053935
## 5 Levels: 0.0248644019011408 0.0284090070053935 ... 0.363644931698218
as.numeric(f)
## [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2
as.integer(f)
## [1] 1 1 3 2 5 …
Run Code Online (Sandbox Code Playgroud) 我导入了一个测试文件并尝试制作直方图
pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
hist <- as.numeric(pichman$WS)
Run Code Online (Sandbox Code Playgroud)
但是,我从数据集中的值得到不同的数字.本来我以为这是因为我有文字,所以我删除了文字:
table(pichman$WS)
ws <- pichman$WS[pichman$WS!="Down" & pichman$WS!="NoData"]
Run Code Online (Sandbox Code Playgroud)
但是,我仍然得到很高的数字,有没有人有想法?
> X864291X8X74
[1] 8.0000000000 9.0000000000 10.0000000000 6.0000000000 8.0000000000
10 Levels: 0.0000000000 10.0000000000 12.0000000000 3.0000000000 4.0000000000 6.0000000000 ... NULL
> as.numeric(X864291X8X74)
[1] 8 9 2 6 8
Run Code Online (Sandbox Code Playgroud)
我误解了什么?不应该是as.numeric 8 9 10 6 8的结果?
如何获得正确的结果?
我读过一个文本文件,其中一些带有实数的列被读作数据帧的因子.如何将factoe列转换为数字列
给定一个shapefile,我如何塑造和使用数据文件,以便能够使用与shapefile中的形状区域对应的标识符来绘制专题图?
#Download English Government Office Network Regions (GOR) from:
#http://www.sharegeo.ac.uk/handle/10672/50
tmp_dir = tempdir()
url_data = "http://www.sharegeo.ac.uk/download/10672/50/English%20Government%20Office%20Network%20Regions%20(GOR).zip"
zip_file = sprintf("%s/shpfile.zip", tmp_dir)
download.file(url_data, zip_file)
unzip(zip_file, exdir = tmp_dir)
library(maptools)
#Load in the data file (could this be done from the downloaded zip file directly?
gor=readShapeSpatial(sprintf('%s/Regions.shp', tmp_dir))
#I can plot the shapefile okay...
plot(gor)
#and I can use these commands to get a feel for the data...
summary(gor)
attributes(gor@data)
gor@data$NAME
#[1] North East North West
#[3] Greater London Authority West Midlands
#[5] Yorkshire …
Run Code Online (Sandbox Code Playgroud) 我有一个R数据帧,其中一列是其级别具有隐式排序的因子.如何以下列方式将因子级别转换为特定整数:
例如,这是我的数据框:
agree <- c("Strongly agree", "Somewhat disagree", "Somewhat agree",
"Neutral", "Strongly agree", "Strongly disagree", "Neutral")
age <- c(41, 35, 29, 42, 31, 22, 58)
df <- data.frame(age, agree)
df
# age agree
# 1 41 Strongly agree
# 2 35 Somewhat disagree
# 3 29 Somewhat agree
# 4 42 Neutral
# 5 31 Strongly …
Run Code Online (Sandbox Code Playgroud)