R、 使用Read.csv一步读取数字形式的字符



我正在用几种不同的变量类型将.csv读取到R中,其中两种是以字符形式读取的,尽管它们是数字(纬度和经度以十进制为单位)。为了解决这个问题,我在阅读后将它们定义为".number"。有更优雅的方法吗?也许是在调用"read.csv"时?

d <- read.csv("data.csv",stringsAsFactors=F)
> str(d)
'data.frame':   467674 obs. of  7 variables:
 $ station     : chr  "USC00036506" "USC00036506" "USC00036506" "USC00036506" ...
 $ station_name: chr  "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" ...
 $ lat         : chr  "35.25" "35.25" "35.25" "35.25" ...
 $ lon         : chr  "-91.75" "-91.75" "-91.75" "-91.75" ...
 $ tmax        : int  50 50 39 100 72 61 -17 -44 6 0 ...
 $ tmin        : int  -39 -39 -89 -61 -6 -83 -144 -150 -161 -128 ...
 $ tobs        : int  33 22 17 61 61 -78 -50 -94 -22 -11 ...
d$lat <- as.numeric(d$lat)
d$lon <- as.numeric(d$lon)
> str(d)
'data.frame':   467674 obs. of  7 variables:
 $ station     : chr  "USC00036506" "USC00036506" "USC00036506" "USC00036506" ...
 $ station_name: chr  "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" "SEARCY AR US" ...
 $ lat         : num  35.2 35.2 35.2 35.2 35.2 ...
 $ lon         : num  -91.8 -91.8 -91.8 -91.8 -91.8 ...
 $ tmax        : int  50 50 39 100 72 61 -17 -44 6 0 ...
 $ tmin        : int  -39 -39 -89 -61 -6 -83 -144 -150 -161 -128 ...
 $ tobs        : int  33 22 17 61 61 -78 -50 -94 -22 -11 ...

您可以设置列类。试试这个:

cls <- c(lat="numeric", lon="numeric")
read.csv("data.csv", colClasses=cls, stringsAsFactors=FALSE)

注意:未经测试,因为您不提供测试数据。

我终于发现了问题所在。"NA"在原始文件中被编码为"未知"(在读入R之前)。我现在意识到我是相当密集。感谢大家的耐心和帮助。这是我最终使用的代码:

d <- read.csv("data.csv",stringsAsFactors=F, na.strings="unknown")

最新更新