作者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://www.ptt.cc/bbs/R_Language/M.1504967499.A.46E.html
※ 編輯: celestialgod (125.224.99.119), 09/09/2017 22:40:21
推 locka: 推lubridate~好用 09/09 22:44
推 swilly0906: 謝謝版主大大 學到很多 讚讚!! 09/10 00:29