【问题标题】:Read data in form '1.4523e-9'以“1.4523e-9”形式读取数据
【发布时间】:2015-04-10 22:52:58
【问题描述】:

我正在尝试使用read.tableread.csv*.txt*.csv 文件中的数据读入R。但是,我的数据写为 e.g. 1.4523e-9 在文件中表示 1.4523*10^{-9} 尽管 ggplot 将其识别为字符串而不是实数。是否有某种eval( )-function 可以将其转换为正确的值?

【问题讨论】:

  • 你试过as.numeric吗?
  • 我猜你需要用str()检查你的数据集
  • @CactusWoman as.numeric 停在. 1.4523e-9 读作1
  • @CactusWoman @MaratTalipov 一个解决方案似乎as.numeric(as.character(...)) 但这看起来很麻烦。
  • 您的数据究竟是什么格式?因为 as.numeric("1.4523e-9") 返回数字 1.4523e-09。如果您的数据是因子形式,您可以尝试使用 read.csv/read.table 的 stringsAsFactors 参数将它们作为字符串读取

标签: r csv type-conversion


【解决方案1】:

根据您导入的csv 文件的确切格式,read.csvread.table 通常只需将所有列转换为因子。由于直接转换为数字失败,我认为这是您的问题。您可以使用 colClasses 参数更改此设置:

# if every column should be numeric:
df <- read.csv("foobar.csv", colClasses = "numeric")

#if only some columns should be numeric, use a vector.
#to read the first as factor and the second as numeric:
read.csv("foobar.csv", colClasses = c("factor", "numeric")

当然,以上两个都是准系统示例;您可能还想提供其他参数,例如header = T

如果您不想在阅读表格时提供每列的类(也许您还不知道它们!),您可以使用以下任一方法进行转换:

df$a <- as.numeric(as.character(a)) #as you already discovered
df$a <- as.numeric(levels(df$a)[df$a])

是的,这些都很笨重,但它们是标准的并且经常recommended.

【讨论】:

    猜你喜欢
    • 2011-03-31
    • 1970-01-01
    • 2019-04-16
    • 2018-04-06
    • 2021-05-25
    • 2013-03-05
    • 2016-05-27
    • 2017-01-03
    • 2012-08-18
    相关资源
    最近更新 更多