0

I'm trying to convert a character column to a date column by using the as.Date function. It works when I enter as.Date(data$colname). However, when I enter as.Date(data[,"colname"]) is returns

do not know how to convert 'data[,"colname"]' to class “Date”

  1. Why does it not work for the second option?
  2. How can I change the second option so that it works?

At the end I want to use the as.Date in a function with the column name as an argument. In that way I don't see how I can use $.

Thanks!

Sample of my data:

structure(list(colname = structure(c(1014036051, 1034089765, 
1237297478, 1260283949, 1274454601, 1580486457.445, 1581671766.241, 
1401445496, 1279550892, 1173094955), tzone = "UTC", class = c("POSIXct", 
"POSIXt"))), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))
Michieldo
  • 169
  • 1
  • 2
  • 15
  • 2
    Hi Michieldo. Can you provide a little sample of data that reproduces this error? – Allan Cameron Sep 20 '20 at 16:38
  • Try `as.Date(data[,"colname",drop=F])` – Duck Sep 20 '20 at 16:42
  • Hi @AllanCameron, I have included a sample of my date column. – Michieldo Sep 20 '20 at 16:50
  • @Duck I have tried your way, but it returns the same error. – Michieldo Sep 20 '20 at 16:50
  • 2
    Try `as.Date(data[["colname"]])` – Duck Sep 20 '20 at 16:53
  • @Duck's first suggestion fails because it should drop to the simpler dimension and become a vector, not a tabular object like `data[, "colname"]`. Try `as.Date(data[, "colname", drop = TRUE])`. See also [Difference between `[` and `[[`](https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el). – Rui Barradas Sep 20 '20 at 16:55

1 Answers1

0

You can pass column names in as function arguments and refer to them with df[[col]]:

df <- data.frame(a = c("2020-01-01", "2020-02-01"), b = 4:5, stringsAsFactors = F)

class(df$a)
# [1] "character"

convert_to_date_type <- function(data, col) as.Date(data[[col]], "%Y-%m-%d")

df["date"] <- convert_to_date_type(df, "a")

class(df$date)
# [1] "Date"
andrew_reece
  • 20,390
  • 3
  • 33
  • 58