将多个字符列转换为R中的as.Date和time [英] Convert multiple character columns to as.Date and time in R
问题描述
我们有一个任意数据集,称为df:
We have an arbitrary dataset, called df:
enter <- c("2017-01-01", "2018-02-02", "2018-03-03")
guest <- c("Foxtrot","Uniform","Charlie","Kilo")
disposal <- c("2017-01-05", "2018-02-05", "2018-03-09")
rating <- c("60","50","50")
date <- c("2017-04-10", "2018-04-15", "2018-04-20")
clock <- c("16:02:00", "17:02:00", "18:02:00")
rolex <- c("20:10:00", "20:49:00", "17:44:00")
df <- data.frame(enter,guest,disposal,rating,date,clock,rolex, stringsAsFactors = F)
我要完成的工作是更改列 enter ,处置 ,以及使用 dplyr 包从字符到日期的 date 。
因此,我想出了以下内容,只需将它们链接在一起即可:
What I try to accomplish is to change the columns enter, disposal, and date from character to date, using dplyr package. So, I came up with the following, simply by chaining it together:
library(dplyr)
library(chron)
df2 <- df %>% mutate(enter = as.Date(enter, format = "%Y-%m-%d"))
%>% mutate(disposal = as.Date(disposal, format = "%Y-%m-%d"))
%>% mutate(date = as.Date(date, format = "%Y-%m-%d"))
我要的是:需要从哪个 mutant 函数dplyr摆脱多重链接,即当我们有很多带有任意名称的暗示日期的列时?我想按名称指定列,然后应用as.Date函数将其从字符更改为日期。
What I am after is this: which mutate function is needed from dplyr to get rid of the multiple chaining, i.e. when we have lots of columns with arbitrary namings that imply dates? I want to specify the columns by name, and then apply the as.Date function to change them from character to date.
某些不适用于这种情况的操作的解决方案:
Some solutions to different operations that are not applicable to this case:
3: change multiple character columns to date
例如,我已经尝试过,但是没有运气:
For example, I've tried, but with no luck:
df2 <- df %>% mutate_at(data = df, each_of(c(enter, disposal, date)) = as.Date(format = "%Y-%m-%d"))
如以下所示: dplyr更改许多数据类型
注意 clock 和 rolex 列。使用chron软件包只需将它们转换为正确的格式,即时间而不是字符
Notice the clock and rolex columns. Using the chron package simply converts them to the right format, i.e. time instead of character
df2 <- df %>% mutate(clock = chron(times = clock)) %>% mutate(rolex = chron(times = rolex))
如此处建议:
将字符转换为r中的时间
现在,是否可以使用没有所有链接的相同解决方案,尤其是当我们有任意数量的具有不同命名的列等时?
Now, is the same solution available without all the chaining, especially when we have an arbitrary amount of columns with different namings etc.?
推荐答案
您只需要调整 mutate_at
的参数。将 as.Date
的所有其他参数指定为 mutate_at
的参数。
You just need to tweak the arguments of mutate_at
. Any additional arguments to as.Date
are specified as arguments to mutate_at
.
df2 <- df %>% mutate_at(vars(enter,disposal,date), as.Date, format="%Y-%m-%d")
问题的第二部分也有类似的解决方案。
The second part of your question has a similar solution.
df2 <- df2 %>% mutate_at(vars(clock, rolex), function(x) chron(times. = x))
这篇关于将多个字符列转换为R中的as.Date和time的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!