-2

I have the following dataframe with the date of 23/09/15 in a numerical string.

Date     Session
230915       2  
230915       2 
230915       2   
230915       2  
230915       2  
230915       2  

I want to change the "Date" column so that it's "23/09/15". Easiest way I thought to do this was to insert "/" after character 2 and 4.

I tried doing it this way:

sub( '(?<=.{2})', '/', df$Date, perl=TRUE )

But got the error:

Error in data$Date : $ operator is invalid for atomic vectors

Also tried editing the date format with:

df$Date <- as.Date(data1$Date, format="%d/%m/%Y")

The column came back with NA's. Why?

Bonono
  • 827
  • 1
  • 9
  • 18

2 Answers2

2

One way would be to use dmy from lubridate

v1 <- dmy(df1$Date)
v1
#[1] "2015-09-23" "2015-09-23" "2015-09-23" "2015-09-23" "2015-09-23" "2015-09-23"

It might be better to store it as Date format. But, if the format needed is different

format(v1, "%d/%m/%y")
#[1] "23/09/15" "23/09/15" "23/09/15" "23/09/15" "23/09/15" "23/09/15"
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You could do

df <- read.table(header=T, text="Date     Session
230915       2  ")  
gsub( '(..)\\B', '\\1/', df$Date )
# [1] "23/09/15"

or

(x <- as.Date(as.character(df$Date), format="%d%m%y"))
# [1] "2015-09-23"
format(x, "%d/%m/%y")
# [1] "23/09/15"

However, if df is a vector, then there is no $ subsetting option:

df <- df$Date
gsub( '(..)\\B', '\\1/', df$Date )
# Error in df$Date : $ operator is invalid for atomic vectors
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • Could you explain to me what the gsub does there please? – Bonono May 27 '16 at 11:27
  • 1
    It replaces all matches by the match and a forward-slash. A match is any two characters that are not followed by the empty string provided by the edge of a word. – lukeA May 27 '16 at 11:42