如何在数据框中创建秒表时间列(运行时钟)

时间:2018-02-01 21:24:24

标签: r dataframe

我希望在我的数据框中添加一个列,它将在几秒钟内成为一个运行时钟,但看起来像一个时间戳。创建的列如下所示:

  $query = 
 "SELECT option_name, option_value FROM {$GLOBALS['wpdb']->prefix}options"
." WHERE option_name LIKE ("
        ." SELECT"
        ." CONCAT( 'options\_your\_option\_name\_', CAST( REPLACE(option_name, 'options_your_option_name_', '' ) AS INTEGER ), '%' )"
        ." FROM {$GLOBALS['wpdb']->prefix}options"
        ." WHERE"
        ." (option_name LIKE 'options\_your\_option\_name\_%\_subfield\_name')"
        ." AND"
        ." (option_value = 'some subfield value')"
      ." LIMIT 0,1"
." )"
  ;

  $results = $GLOBALS['wpdb']->get_results( $query, ARRAY_A );

  if( !empty($results) ){
    foreach($results as $result){
      //do something with it :)
      echo $result['option_name'] . " => " . $result['option_value'];
      echo "<br>";
    }

  }

任何建议都有帮助。

2 个答案:

答案 0 :(得分:1)

一种解决方案是使用row_number作为秒,并将其转换为小时:分钟:秒。

解决方案1:

 df <- data.frame(sl = 1:1000, value = runif(20, 200, 1000))

  df$stopwatch <- row_number()

  library(lubridate)
  library(dplyr)


  df %>% mutate(stopwatch = seconds_to_period(row_number()))

#       sl    value stopwatch
#..........
#58     58 482.6169       58S
#59     59 706.1599       59S
#60     60 498.2112     1M 0S
#61     61 473.2637     1M 1S
$62     62 843.2440     1M 2S
...........

解决方案2:  使用hms包:

  df %>% mutate(stopwatch = hms::as.hms(row_number()))
       sl    value stopwatch
1       1 473.2637  00:00:01
2       2 843.2440  00:00:02
3       3 864.1852  00:00:03
4       4 854.0714  00:00:04
5       5 425.9075  00:00:05
6       6 505.4091  00:00:06
7       7 507.7273  00:00:07
8       8 440.8840  00:00:08

答案 1 :(得分:1)

虽然使用MKR的解决方案显示的现成功能as.hms可能更简单,但为此编写自己的功能并不困难。这可能更有启发性,并且可以避免依赖。

stopwatch = function(x) {
  sprintf('%02i:%02i:%02i', (x%/%3600), (x%/%60) %% 60, x%%60)
}
stopwatch(1:10)

# [1] "00:00:01" "00:00:02" "00:00:03" "00:00:04" "00:00:05" "00:00:06" "00:00:07" "00:00:08"
# [9] "00:00:09" "00:00:10"