jimjames
jimjames

Reputation: 41

Repeated code, need help creating a function formating and creating new columns in dataframe

I have some different dataframes containing date and need to create and format the data. Step 1. Convert dataframe$date as date. Step 2&3. Create new columns with week and year. Step 4&5 convert week and year to numeric. Since I need to do this multiple times, I would like to create a function out of it.

dataframe$date <- as.Date(dataframe$date, "%Y-%m-%d")
dataframe$week <- strftime(dataframe$date, format = "%V")
dataframe$year <- strftime(dataframe$date, format = "%Y")
dataframe$week <- as.numeric(dataframe$week,as.numeric)
dataframe$year <- as.numeric(dataframe$year,as.numeric)

My attempt:

format.dataframe <- function(a) {

  paste(a, $date, sep="") <- as.Date(paste(a, $date, sep=""), "%Y-%m-%d")
  paste(a, $week, sep="") <- strftime(paste(a, $date, sep=""), format = "%V")
  paste(a, $year, sep="") <- strftime(paste(a, $date, sep=""), format = "%Y")
}

So a should be the name of the dataframe I want to format.

Upvotes: 1

Views: 25

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

You can use transform in base R :

format.dataframe <- function(a) {
  transform(a, date = as.Date(date, "%Y-%m-%d"), 
               week = as.numeric(strftime(date, format = "%V")),
               year = as.numeric(strftime(date, format = "%Y")))
}

a <- format.dataframe(a)

Or with mutate in dplyr :

library(dplyr)

format.dataframe <- function(a) {
  a %>%
    mutate(date = as.Date(date, "%Y-%m-%d"), 
           week = as.numeric(strftime(date, format = "%V")),
           year = as.numeric(strftime(date, format = "%Y")))
}

a <- format.dataframe(a)

Upvotes: 1

Related Questions