作者celestialgod (天)
看板R_Language
标题Re: [问题] 日期与回圈问题
时间Sat Sep 9 22:31:37 2017
※ 引述《swilly0906 (史威利哥哥)》之铭言:
: [问题类型]:
: 程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
: [软体熟悉度]:
: 新手(没写过程式,R 是我的第一次)
: [问题叙述]:
: 我有一个工作的raw data
: 其中有一个column是时间(小时:分钟:秒)
: 现在我想把时间全部变成以分钟表示
: 且超过(含)30秒以上,强制进位一分钟
: [程式范例]:
: library(chron)
: test <- c("01:11:28", "01:01:30", "02:32:31","00:30:42")
: timestest <- times(test)
: 60 * hours(timestest) + minutes(timestest) + round(seconds(timestest)/60)
: #这个ouput输出的vector,就是我要的样式,结果我突然发现round(0.5)竟然不会进位成1
: #所以我只好写回圈了(但我是新手,以前根本没碰过回圈就是了...)
round1 <- function(x){
a <- vector("integer", length(x))
for(i in seq_along(x)) {
if(x[i] < 0.5){
a[i] <- floor(x[i])
} else if(x[i] >= 0.5 & x[i] <= 1){
a[i] <- ceiling(x[i])
}
}
return(a)
}
# 我不熟chron这个套件,但是用data.table应该是差不多意思
library(data.table)
times <- c("01:11:28", "01:01:30", "02:32:31","00:30:42")
timestest <- as.ITime(times)
60 * hour(timestest) + minute(timestest) + round1(second(timestest)/60)
# [1] 71 62 153 31
: round1 <- function(x){
: for(i in 1:length(x)){
: if(x[i]<0.5){
: a <- floor(x[i])
: }
: else if(x[i]>=0.5 & x[i]<=1){
: a<- ceiling(x[i])
: }
: else{
: a <- 1
: }
: print(a)
: }
: }
: 60 * hours(timestest) + minutes(timestest) + round1(seconds(timestest)/60)
: 结果发现output出现错误(应该说不是我要的output)
: 我直接问了,这边到底要怎麽改才对??????????????
: ---------------------------------------------------------------------------
: 後记: 後来我在Stackoverflow找到类似问题,网友说用ifelse就可以了
: 60 * hours(timestest) + minutes(timestest) +
: ifelse(seconds(timestest)/60<0.5,0,1) #这个output就是我要的答案(所以算解决了)
: 但我还是想知道,如果我很顽固,一定要用上面的function处理
: 到底要怎麽写啊??请各位大大救救我QQ
: [关键字]
: #时间单位以分钟单位表示
: #回圈loop
: #function
你也可以试试看这个:
library(lubridate)
times <- c("01:11:28", "01:01:30", "02:32:31","00:30:42")
durations <- as.duration(hms(times))
[email protected] <- round(
[email protected] / 60)
minutes(durations)$minute
# [1] 71 62 153 31
--
R资料整理套件系列文:
magrittr #1LhSWhpH (R_Language) https://goo.gl/72l1m9
data.table #1LhW7Tvj (R_Language) https://goo.gl/PZa6Ue
dplyr(上.下) #1LhpJCfB,#1Lhw8b-s (R_Language) https://goo.gl/I5xX9b
tidyr #1Liqls1R (R_Language) https://goo.gl/i7yzAz
pipeR #1NXESRm5 (R_Language) https://goo.gl/zRUISx
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 125.224.99.119
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1504967499.A.46E.html
※ 编辑: celestialgod (125.224.99.119), 09/09/2017 22:40:21
1F:推 locka: 推lubridate~好用 09/09 22:44
2F:推 swilly0906: 谢谢版主大大 学到很多 赞赞!! 09/10 00:29