0

I am trying to do an if else statement to say if the value is less than 10 add a zero in front, if not leave it as is. I am trying to get all of my dates to be 2 digits. Please assist.

if(df$col < 10){
paste '0'
else df$col
}

I was trying to break it down into different columns

EventID SampleDate SampleTime
130466  3/19/2008   12:30:00
131392  4/30/2008   08:45:00
131658  5/14/2008   10:00:00
117770  6/11/2008   08:45:00
118680  7/23/2008   09:15:00
118903   8/6/2008   09:00:00

SampleDatech year month day2
3/19/2008 2008     3   19
4/30/2008 2008     4   30
5/14/2008 2008     5   14
6/11/2008 2008     6   11
7/23/2008 2008     7   23
 8/6/2008 2008     8    6
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
KerryLee
  • 373
  • 2
  • 5
  • 13
  • Can you show us sample data? There are date formatters which might be a better approach to do this. – Tim Biegeleisen Jul 03 '16 at 00:37
  • 1
    so you are padding with leading 0s? http://stackoverflow.com/questions/14409084/pad-with-leading-zeros-to-common-width – rawr Jul 03 '16 at 01:06
  • No idea what `df$col` is, but be aware that `if` is not vectorized, and `ifelse` strips attributes (like dates). To what is here, though, you should convert them to a date class, e.g. `df$SampleDate <- as.Date(df$SampleDate, format = '%m/%d/%Y')` or a datetime class, e.g. `df$SampleDateTime <- as.POSIXct(paste(df$SampleDate, df$SampleTime), format = '%m/%d/%Y %H:%M:%S')` – alistaire Jul 03 '16 at 01:21
  • `df$col` is not even present in the data you provided. And `paste '0'` is not valid R syntax. And what @alistaire said. Voting to close as unclear. – Rich Scriven Jul 03 '16 at 02:55

1 Answers1

0

If you are trying to output just the day with a leading zero to a new column, you can use a combination of strftime and as.Date.

df$day = strftime(as.Date(df$SampleDate, "%m/%d/%Y"), "%d")

Or if you want to keep the whole date, but add the leading zero to the day you can do this.

df$NewDate = strftime(as.Date(df$SampleDate, "%m/%d/%y"), "%m/%d/%Y")

Jacob F
  • 366
  • 1
  • 6