dplyr的过滤器不适用于lubridate的时间格式? [英] dplyr's filter not working on lubridate's timeformats?

查看:71
本文介绍了dplyr的过滤器不适用于lubridate的时间格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试回答此问题时,我会跑解决在lubridat-期间列上使用dplyr -package中的filter的问题.

When trying to answering this question, I run against a problem with using filter from dplyr-package on a lubridat-period column.

示例数据:

df <- data.frame(time = ms(c('0:19','1:24','7:53','11:6')), value = 1:4)

使用:

filter(df, time > ms('5:00'))
# or:
filter(df, time > '5M 00S')

导致错误的输出:

   time value
1   53S     3
2 1M 6S     4
Warning message:
In format.data.frame(x, digits = digits, na.encode = FALSE) :
  corrupt data frame: columns will be truncated or padded with NAs

此答案中应用解决方案并不会得到正确的输出:

Applying the solution from this answer doesn't also result in the correct output:

> df %>% 
+   mutate(time = format(time, '%M:%S')) %>% 
+   filter(time > '05:00')
    time value
1    19S     1
2 1M 24S     2
3 7M 53S     3
4 11M 6S     4

但是使用普通的R方法,可以工作:

But using vanilla R methods, do work:

> df[df$time > ms('5:00'), ]
    time value
3 7M 53S     3
4 11M 6S     4

> subset(df, time > ms('5:00'))
    time value
3 7M 53S     3
4 11M 6S     4

dplyr方法中我有做错什么吗?

Is there anything I'm doing wrong in my dplyr approach?

推荐答案

尝试了许多不同的方法后,我得到了dplyr唯一的解决方案:

After trying a lot of different methods I get a dplyr only solution:

df %>% 
  mutate(time = as.numeric(time)) %>% 
  filter(time > as.numeric(ms('5:00'))) %>% 
  mutate(time = ms(paste0(floor(time/60),':',round((time/60 - floor(time/60))*60))))

这将带来良好的结果:

    time value
1 7M 53S     3
2 11M 6S     4

这篇关于dplyr的过滤器不适用于lubridate的时间格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆