Convert factor to date class for multiple columns

前端 未结 1 715
生来不讨喜
生来不讨喜 2020-12-07 03:49

I have 7 columns in my dataset. I want to convert 4 variables (2 to 5 column) from factor to date format. I can do it one column at a time, but I want to know if there is a

相关标签:
1条回答
  • 2020-12-07 04:18

    Given the format of your dates, you may try this:

    # sample data
    df <- data.frame(a = 1:2,
                     d1 = factor(c("2013/01/01", "2014/01/01")),
                     d2 = factor(c("2013/01/01", "2014/01/01")),
                     b = 3:4)
    
    df[ , 2:3] <- lapply(df[ , 2:3], as.Date)
    
    str(df)
    # 'data.frame':  2 obs. of  4 variables:
    # $ a : int  1 2
    # $ d1: Date, format: "2013-01-01" "2014-01-01"
    # $ d2: Date, format: "2013-01-01" "2014-01-01"
    # $ b : int  3 4
    
    0 讨论(0)
提交回复
热议问题