将 data.frame 中的列转换为日期 [英] Convert column in data.frame to date

查看:33
本文介绍了将 data.frame 中的列转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框

a1 <- c("a","a","b","b","c","d","e","e")b2 <- c("01.01.2015", "02.02.2015", "14.02.2012", "16.08.2008", "17.06.2003", "31.01.2015", "07.01.209.205".2001")c3 <- c("1a", "2b", "3c", "4d", "5e", "6f", "7g", "8h")d3 <- c(1:8)df2 <- data.frame(a1,b2,c3,d3,stringsAsFactors = F)

我的代码.

库(dplyr)图书馆(magrittr)测试<-df2%>%group_by(a1)%>%as.Date(b2, format = "%d.%m.%Y")

<块引用>

as.Date.default(., b2, format = "%d.%m.%Y") 中的错误:不知道如何转换'.'对日期"进行分类

好吧,我试过没有管道:

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

<块引用>

df$b2 中的错误:'closure' 类型的对象不可子集

第一:为什么我会收到两条不同的错误消息,因为我(就我的理解)正在做同样的事情?

第二,为什么我不能将我的专栏转换为日期?!

我可能应该补充一点,我知道使用 mutate 将列更改为 date 格式.但我想知道为什么我的方法不起作用.

解决方案

mutate

内进行转换

df2 %>%group_by(a1)%>%变异(b2=as.Date(b2,格式=%d.%m.%Y"))# a1 b2 c3 d3# (chr) (日期) (chr) (int)#1 a 2015-01-01 1a 1#2 a 2015-02-02 2b 2#3 b 2012-02-14 3c 3#4 b 2008-08-16 4d 4#5 c 2003-06-17 5e 5#6 d 2015-01-31 6f 6#7 e 2022-01-07 7g 7#8 e 2001-05-09 8h 8

如果我们只需要做转换,我们不需要按'a1'分组.

mutate(df2, b2= as.Date(b2, format= "%d.%m.%Y"))

通过使用 magrittr 中的 %<>% 操作符,我们可以就地转换.

df2 %<>%变异(b2= as.Date(b2,格式=%d.%m.%Y"))

My dataframe

a1 <- c("a","a","b","b","c","d","e","e")
b2 <- c("01.01.2015", "02.02.2015", "14.02.2012", "16.08.2008", "17.06.2003", "31.01.2015", "07.01.2022", "09.05.2001")
c3 <- c("1a", "2b", "3c", "4d", "5e", "6f", "7g", "8h")
d3 <- c(1:8)

df2 <- data.frame(a1,b2,c3,d3, stringsAsFactors = F)

My code.

library(dplyr)
library(magrittr)

test <- df2 %>%
    group_by(a1) %>% 
    as.Date(b2, format = "%d.%m.%Y")

Error in as.Date.default(., b2, format = "%d.%m.%Y") : do not know how to convert '.' to class "Date"

Well, I tried without the pipe:

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

Error in df$b2 : object of type 'closure' is not subsettable

First: Why do I get two different error messages since I am (for my understanding) am doing the same?

Second, why cant I convert my column to date?!

I might should add that I am aware of using mutate to alter the column as date format. But I wonder why my approach is not working.

解决方案

Do the transformations within mutate

df2 %>%
   group_by(a1) %>%
   mutate(b2=as.Date(b2, format = "%d.%m.%Y"))
#    a1         b2    c3    d3
#  (chr)     (date) (chr) (int)
#1     a 2015-01-01    1a     1
#2     a 2015-02-02    2b     2
#3     b 2012-02-14    3c     3
#4     b 2008-08-16    4d     4
#5     c 2003-06-17    5e     5
#6     d 2015-01-31    6f     6
#7     e 2022-01-07    7g     7
#8     e 2001-05-09    8h     8

If we need to do only the transformation, we don't need to group by 'a1'.

mutate(df2, b2= as.Date(b2, format= "%d.%m.%Y"))

By using %<>% operator from magrittr, we can transform in place.

df2 %<>%
  mutate(b2= as.Date(b2, format= "%d.%m.%Y"))

  

这篇关于将 data.frame 中的列转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆