简体   繁体   English

在 R 中读取 CSV 文件并格式化日期和时间,同时读取并避免标记为的缺失值?

[英]Reading CSV file in R and formatting dates and time while reading and avoiding missing values marked as?

I am trying to Reading CSV file in R .我正在尝试在 R 中读取 CSV 文件。 How can I read and format dates and times while reading and avoid missing values marked as ?.如何在阅读时阅读和格式化日期和时间并避免丢失标记为 ? 的值。 The data I load after reading should be clean.我读取后加载的数据应该是干净的。

I tried something like data <- read.csv("Data.txt") It worked, but the dates and times were as is.我尝试了类似data <- read.csv("Data.txt")它起作用了,但日期和时间保持原样。

Also how can I extract a subset of data from specific data range?另外,如何从特定数据范围中提取数据子集?

For this I tried something like为此,我尝试了类似的东西

subdata <- subset(data, 
                  Date== 01/02/2007 & Date==02/02/2007, 
                  select = Date:Sub_metering_3)

I get error Error in eval(expr, envir, enclos) : object 'Date' not foundError in eval(expr, envir, enclos) : object 'Date' not found收到错误Error in eval(expr, envir, enclos) : object 'Date' not found

Date is the first column.日期是第一列。

The functions read.csv() and read.table() are not set up to do detailed fancy conversion of things like dates that can have many formats.函数read.csv()read.table()没有设置为对日期等可以有多种格式的东西进行详细的花哨转换。 When these functions don't automatically do what's wanted, I find it best to read the data in as text and then convert variables after the fact.当这些函数没有自动执行所需的操作时,我发现最好以文本形式读取数据,然后在事后转换变量。

data <- read.csv("Data.txt",colClasses="character",na.strings="?")
data$FixedDate <- as.Date(data$Date,format="%Y/%m/%d")

or whatever your date format is.或任何您的日期格式。 The variable FixedDate will then be of type Date and you can use equality and other conditions to subset.变量FixedDate将是Date类型,您可以使用相等和其他条件进行子集。

Also, in your example code you are putting 01/02/2007 as bare code, which results in dividing 1 by 2 and then by 2007 yielding 0.0002491281, rather than inserting a meaningful date.此外,在您的示例代码中,您将01/02/2007作为裸代码,这导致 1 除以 2,然后除以 2007 产生 0.0002491281,而不是插入有意义的日期。 Consider as.Date("2007-01-02") instead.考虑as.Date("2007-01-02")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM