0

I have the following toy data.table

 x = data.table(dt = c('2015-01-01','2015-02-01','2016-04-01'))

I'm trying to add an extra column to the table which has the three letter abbreviation of the date. I tried

 x$dt = strptime(x$dt,'%b')

but it gave back the following, a warning and an empty field.

Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 9 items to be assigned to 3 items of column 'dt' (6 unused)
2: In `[<-.data.table`(x, j = name, value = value) :
  Coerced 'list' RHS to 'character' to match the column's type. Either    change the target column to 'list' first (by creating a new 'list' vector length 3 (nrows of entire table) and assign that; i.e. 'replace' column), or coerce RHS to 'character' (e.g. 1L, NA_[real|integer]_, as.*, etc) to make your intent clear and for speed. Or, set the column type correctly up front when you create the table and stick to it, please.

> x
          dt mnth
1: c(NA, NA, NA)     
2: c(NA, NA, NA)     
3: c(NA, NA, NA)     

I found prior Q&A on SO that said that strptime returned a list but haven't been able to accomplish this relatively simple task. Could someone provide some pointers?

broccoli
  • 4,738
  • 10
  • 42
  • 54

1 Answers1

3

We can use format

format(strptime(x$dt, '%Y-%m-%d'), '%b')

Or as @Frank mentioned, the format.Date can be applied to Date class

format(as.Date(x$dt), "%b")
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    There's a `format.Date` method, and `as.Date` correctly parses the string, so `format(as.Date(x$dt), "%b")` is another option. Or, as Jaap mentioned, `months(as.Date(x$dt), abbr = TRUE)` – Frank Feb 20 '16 at 22:37