在多列的数据框中转换具有不同格式的日期 [英] Convert dates with different formats in data frame over multiple columns

查看:102
本文介绍了在多列的数据框中转换具有不同格式的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框(测试):

I have data frame (test) that looks like this:

    abx   start      stop       abx2    start2     stop2     abx3 start3 stop3
    cipro 07/10/12   07/10/12   flagyl  07/10/12   07/17/12   n/a   n/a   n/a
    vanco 07/12/2012 07/15/2012 levo    07/20/2012 07/27/2012 n/a  n/a    n/a

此过程一直持续到start9/stop9.我想将所有日期转换为标准日期格式.

This continues until start9/stop9. I'd like to convert all the dates to standard date format.

我写了一个函数,根据日期中的字符数来转换开始日期.计划为停靠点编写类似的功能.

I wrote a function to convert the start dates depending on the number of characters in the date. Plan to write a similar function for the stops.

    dateconv <- function(x) { 
    as.character(x)
    z <- ifelse(nchar(x) == 8, "y","Y")
    date <- as.Date(x, format =paste0("%m/%d/%", z))
    rm(z)
    }
    test[,grep("^start", names(test))] <- dateconv(test[,grep("^start",         
   names(test))])

有什么主意我做错了吗?出现此错误: as.Date.default(x,format = paste0(%m/%d/%",z))中的错误: 不知道如何将"x"转换为日期"类

Any ideas what I'm doing wrong? Getting this error: Error in as.Date.default(x, format = paste0("%m/%d/%", z)) : do not know how to convert 'x' to class "Date"

更新(2015年2月20日): 多亏了Richard的评论,我才能做到这一点(真的就像grep("st(art | op)":

Update (Feb 20, 2015): Thanks to Richard's comment I got this to work (really like the grep("st(art|op)" :

    g <- grep("st(art|op)", names(test), value = TRUE)

    test[g] <- lapply(test[g], function(x) {
     x <- as.character(x)
      as.Date(x, format = paste0("%m/%d/%", ifelse(nchar(x) == 8, "y",       "Y")))})

推荐答案

这是更改test数据帧的一种方法.

Here's one way to change the test data frame.

g <- grep("st(art|op)", names(test), value = TRUE)

test[g] <- lapply(test[g], function(x) {
    x <- as.character(x)
    as.Date(x, format = paste0("%m/%d/%", ifelse(nchar(x) == 8, "y", "Y")))
}))

给出

#     abx      start       stop   abx2     start2      stop2 abx3 start3 stop3
# 1 cipro 2012-07-10 2012-07-10 flagyl 2012-07-10 2012-07-17  n/a   <NA>  <NA>
# 2 vanco 2012-07-12 2012-07-15   levo 2012-07-20 2012-07-27  n/a   <NA>  <NA>

test在哪里

test <- read.table(text = "abx   start      stop       abx2    start2     stop2     abx3 start3 stop3\n    cipro 07/10/12   07/10/12   flagyl  07/10/12   07/17/12   n/a   n/a   n/a\n    vanco 07/12/2012 07/15/2012 levo    07/20/2012 07/27/2012 n/a  n/a    n/a", header = TRUE, stringsAsFactors=FALSE)

这篇关于在多列的数据框中转换具有不同格式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆