R润滑:将帮助程序应用于数据框

问题描述 投票:1回答:2

我有一个类似这样的时间数据框:

library(lubridate)

times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"), 
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")), 
                        row.names = c(NA, 3L), class = "data.frame")

我想在更方便的日期时间对象中转换时间,我将使用hms()包中的lubridate辅助函数进行此操作。

在数据框的一列上运行hms()就像一个超级按钮:

hms(times[,1])

[1]“ 17H 19M 4S”“ 17H 28M 53S”“ 17H 38M 44S”

太好了,我当然可以在整个数据帧上使用apply()

apply(times, 2, hms)

哪个给出了一个带有一些整数的怪异数据框,绝对不是我所期望的。

times函数转换我的所有hms()数据帧的正确方法是什么?

r lubridate
2个回答
2
投票

代替apply,可以使用lapply,因为apply转换为matrix,并且它不包含hms创建的属性

library(lubridate)
times[] <- lapply(times, hms)
str(times)
#'data.frame':  3 obs. of  2 variables:
# $ exp1:Formal class 'Period' [package "lubridate"] with 6 slots
#  .. ..@ .Data : num  4 53 44
#  .. ..@ year  : num  0 0 0
#  .. ..@ month : num  0 0 0
#  .. ..@ day   : num  0 0 0
#  .. ..@ hour  : num  17 17 17
#  .. ..@ minute: num  19 28 38
# $ exp2:Formal class 'Period' [package "lubridate"] with 6 slots
#  .. ..@ .Data : num  4 53 45
#  .. ..@ year  : num  0 0 0
#  .. ..@ month : num  0 0 0
#  .. ..@ day   : num  0 0 0
#  .. ..@ hour  : num  17 17 17
#  .. ..@ minute: num  22 31 41

2
投票
library(dplyr)
times %>% mutate_all(hms)
     exp1        exp2
#1  17H 19M 4S  17H 22M 4S
#2 17H 28M 53S 17H 31M 53S
#3 17H 38M 44S 17H 41M 45S
© www.soinside.com 2019 - 2024. All rights reserved.