R,使用 read.csv 一步读取字符为数字?

问题描述 投票:0回答:2

我正在将 .csv 读入 R 中,其中有几种不同的变量类型,其中两种变量类型虽然是数字(以十进制表示的纬度和经度),但还是作为字符读入。为了解决这个问题,我在读入它们后将它们定义为“as.numeric”。有没有更优雅的方法来做到这一点?也许在“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 ...
r import read.table
2个回答
11
投票

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

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

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


2
投票

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

d <- read.csv("data.csv", stringsAsFactors = F, na.strings = "unknown")
© www.soinside.com 2019 - 2024. All rights reserved.