函数read.table和应用功能到列 [英] read.table and apply functions to a column
问题描述
我读函数read.table使用Apache的日志文件,我想知道,如果它在某种程度上可以应用功能(即strptime),而数据正在进口的,而不是后期处理它。
I am reading an apache logfile using read.table and am wondering if it's somehow possible to apply a function (i.e. strptime ) while the data are being imported, instead of post-processing it.
的要求的更多细节:
包含日期列的格式为:
More details as requested: The column containing the date has the format:
[10/Nov/2011:06:25:14
我可以用成功解析:
I can successfully parse it using:
strptime(red[1,4],format="[%d/%b/%Y:%H:%M:%S")
或
as.POSIXct(strptime(red[1,4],format="[%d/%b/%Y:%H:%M:%S"))
但
as.POSIXct(red[1,4],format="[%d/%b/%Y:%H:%M:%S")
失败。因此,我不能在colClasses AFAIK使用POSIXct。
fails. Hence I cannot use POSIXct in colClasses AFAIK.
推荐答案
如果有一个为
方法,你可以使用colClasses与类。由于日期是一类,具有YYYY-MM-DD的默认格式,如果你的日期是在格式,你可以只包括在 colClasses
矢量日期。也可以定义新的 as.function
的。一如往常,更详细的您提供的有关问题,更好的答案。
If there is an as.
method you can use colClasses with that class. Since Date is a class and has a default format of YYYY-MM-DD, if your dates are in that format, you could just include Date in the colClasses
vector. It is also possible to define new as.function
's. As always, the more detail you supply about the problem, the better the answer.
library(methods)
setClass("logDate")
#[1] "logDate"
setAs("character", "logDate", function(from)
as.POSIXct(from, format="[%d/%b/%Y:%H:%M:%S"))
DF <- read.table(textConnection("[10/Nov/2011:06:25:14"), header = FALSE,
colClasses = c("logDate"))
str(DF)
#'data.frame': 1 obs. of 1 variable:
# $ V1: POSIXct, format: "2011-11-10 06:25:14"
也许应该给格罗腾迪克的Gabor一些信贷,因为他是一个谁教我如何这个5年前做的事:
的https://www.stat.math.ethz ·CH / pipermail / R-帮助/ 2007月/ 130912.html
这篇关于函数read.table和应用功能到列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!