我正在尝试学习R,并且我遇到了关于将数据集中的一列从整数值转换为时间的问题.
上述专栏以5分钟的分数打破了这些日子.使用以下格式:5将是00:05,105将是01:05而1105将是11:05.
如果我使用:
strptime(activity[,"interval"],format="%H%M")
Run Code Online (Sandbox Code Playgroud)
对于低于1000的所有值,结果对象返回"NA".
关于如何使用apply family进行相同过程的任何想法都将不胜感激
我知道这是一个非常基本的问题,但我自己无法弄清楚.
非常感谢你
编辑:根据请求,活动[n,"interval"]列(此列有17568行,包括5到2355的数字,持续数天),15个第一个元素如下所示:
activity[1:15,"interval"]
[1] 0 5 10 15 20 25 30 35 40 45 50 55 100 105 110
Run Code Online (Sandbox Code Playgroud)
应该看起来像这样
activity[1:15,"interval"]
[1] 0000 0005 0010 0015 0020 0025 0030 0035 0040 0045
[11] 0050 0055 0100 0105 0110
Run Code Online (Sandbox Code Playgroud)
这是一个建议
temp <- c(0 , 5 , 10, 15 ,20 , 25 ,30 ,35, 40, 45 , 50 ,55 ,100 ,105, 110) # Your data
temp2 <- mapply(function(x, y) paste0(rep(x, y), collapse = ""), 0, 4 - nchar(temp))
temp <- paste0(temp2, temp)
temp
# [1] "0000" "0005" "0010" "0015" "0020" "0025" "0030" "0035" "0040" "0045" "0050" "0055" "0100" "0105" "0110"
Run Code Online (Sandbox Code Playgroud)
那你可以做
format(strptime(temp, format="%H%M"), format = "%H:%M")
#[1] "00:00" "00:05" "00:10" "00:15" "00:20" "00:25" "00:30" "00:35" "00:40" "00:45" "00:50" "00:55" "01:00" "01:05" "01:10"
Run Code Online (Sandbox Code Playgroud)
使用@David Arenburg代码的略微修改版本sprintf(参见此博客文章中的差异paste和sprint:http://trinkerrstuff.wordpress.com/2013/09/15/paste-paste0-and-sprintf-2/ )"
temp <- c(0 , 5 , 10, 15 ,20 , 25 ,30 ,35, 40, 45 , 50 ,55 ,100 ,105, 110) # Your data
temp <- sprintf("%04d", temp)
## [1] "0000" "0005" "0010" "0015" "0020" "0025" "0030" "0035"
## [9] "0040" "0045" "0050" "0055" "0100" "0105" "0110"
format(strptime(temp, format="%H%M"), format = "%H:%M")
## [1] "00:00" "00:05" "00:10" "00:15" "00:20" "00:25" "00:30" "00:35"
## [9] "00:40" "00:45" "00:50" "00:55" "01:00" "01:05" "01:10"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9336 次 |
| 最近记录: |