【问题标题】:lapply, data wrangling dates, unexpected outputlapply,数据争吵日期,意外输出
【发布时间】:2018-07-24 05:00:12
【问题描述】:

我有一个数据集 (CSV),其中一列包含多种日期格式,可以是

|birth_date|
------------
|DD/MM/YYYY|
|YYYY-MM-DD|
| YYYY     |
| [BLANK]  |

我正在尝试将“YYYY-MM-DD”格式的日期更改为“DD/MM/YYYY”。到目前为止,我有以下代码:

# Loading in required libraries
library(tidyverse)
source("R/formatDate.R")

# Reading in the Nobel Prize data
data <- read_csv('datasets/data1.csv')

fixed_birthdates <- lapply(data["birth_date"], function(x) formatDate(x))$birth_date
data[["birth_date"]] <- fixed_birthdates

格式日期.R:

formatDate <- function(x) {
  output <- x
  if (grepl('-', x, fixed = TRUE)) {
    xx <- strsplit(x,'-',TRUE)
    output <- paste(xx[3],xx[2],xx[1],sep="/")
  }
  return(output)
}

但是每次我运行它时,fixed_birthdates 的值都等于"c(\"1854\", \"03\", \"15\")/c(\"1839\", \"03\", \"16\")/c(\"1852\", \"08\", \"30\")"。该变量有 5 个元素,而我的原始数据集有 969 个。不知道为什么会这样。

我试图实现的逻辑很简单,但是我不知道如何在 R 中表达它。使用 c# 代码它看起来像这样:

string formatDate (string x)
{
    string output = x;
    if (x.Contains("-"))
    {
        string[] xx = x.Split('-');
        output = xx[1]+'/'+xx[2]+'/'+xx[3];
    }
    return output;
}

【问题讨论】:

    标签: r function


    【解决方案1】:

    您可以尝试通过as.Date 格式化,然后覆盖成功解析的值。这是一个简单的例子:

    data <- data.frame(
      birth_date = c("01/01/2001", "2010-03-14", "1982", ""),
      stringsAsFactors=FALSE
    )
    #  birth_date
    #1 01/01/2001
    #2 2010-03-14
    #3       1982
    #4
    
    frmtdate <- as.Date(data$birth_date, format="%Y-%m-%d")
    data$birth_date[!is.na(frmtdate)] <- format(frmtdate[!is.na(frmtdate)], "%d/%m/%Y")
    data
    #  birth_date
    #1 01/01/2001
    #2 14/03/2010
    #3       1982
    #4
    

    【讨论】:

      【解决方案2】:

      strsplit 的输出是list。我们可以向量化而不是循环遍历每个元素,但是可以通过使用 [[ 提取 list 元素来纠正 OP 的代码

      formatDate <- function(x) {
        output <- x
        if (grepl('-', x, fixed = TRUE)) {
          xx <- strsplit(x,'-',TRUE)
          output <- paste(xx[[1]][3],xx[[1]][2],xx[[1]][1],sep="/")
        }
        return(output)
      }
      
      data[,"birth_date"] <- sapply(data[,"birth_date"], function(x) formatDate(x))
      data[, "birth_date"]
      #[1] "01/01/2001" "14/03/2010" "1982"       ""    
      

      【讨论】:

      • 这有点像我期望的解决方案。但上面的代码将所有日期更改为第一个birth_date 值(格式正确)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      相关资源
      最近更新 更多