将因子转换为多列的日期类(Convert factor to date class for multiple columns)

编程入门 行业动态 更新时间:2024-10-28 14:29:40
因子转换为多列的日期类(Convert factor to date class for multiple columns)

我的数据集中有7列。 我想从因子到日期格式转换4个变量(2到5列)。 我一次只能做一列,但我想知道是否有一条捷径可以将它们全部转换到一起。

目前这是我如何做到的。

SampleData$column2<-as.Date(SampleData$column2,format="%Y/%m%/%d") SampleData$column3<-as.Date(SampleData$column3,format="%Y/%m%/%d") SampleData$column4<-as.Date(SampleData$column4,format="%Y/%m%/%d") SampleData$column5<-as.Date(SampleData$column5,format="%Y/%m%/%d")

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 shortcut through which I can convert all of them together.

Currently this is how I do it.

SampleData$column2<-as.Date(SampleData$column2,format="%Y/%m%/%d") SampleData$column3<-as.Date(SampleData$column3,format="%Y/%m%/%d") SampleData$column4<-as.Date(SampleData$column4,format="%Y/%m%/%d") SampleData$column5<-as.Date(SampleData$column5,format="%Y/%m%/%d")

最满意答案

鉴于你的日期格式,你可以试试这个:

# 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

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

更多推荐

本文发布于:2023-07-26 02:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1269634.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:因子   转换为   日期   Convert   factor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!