【问题标题】:R, Read in characters as numeric in one step using read.csv?R,使用read.csv一步读取字符作为数字?
【发布时间】:2013-06-30 17:49:18
【问题描述】:

我正在将 .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 ...

【问题讨论】:

  • 使用colClasses 参数设置列类。
  • 我认为你的 long 和 lat 列中可能有一些东西弄乱了函数,阻止它读取数值。也许是一个奇怪的NA?至少一个单元格中的十进制值的逗号?
  • 是的,@RomanLuštrik,纬度​​/经度列中有 NA。
  • 这就是为什么(我猜)@Andrie 使用 colClasses 的建议不起作用...我收到以下错误:扫描错误(文件,什么,nmax,sep,dec,quote,跳过,nlines,na.strings,:scan() 预期为“真实”,得到“未知”
  • @seapen NA 是如何编码的? "NA"?还是别的什么?

标签: r import read.table


【解决方案1】:

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

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")
    

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      相关资源
      最近更新 更多