将因子转换为多列的日期类(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 4Given 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更多推荐
发布评论