R语言 如何把小时变成一刻钟

wz3gfoph  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(85)

我有价值观 在数据框中显示以下小时(天):0,1,2,3,4,...,23.但是我想把这些小时分成四分之一小时00:15,00:30,00:45,...,23:45,00:00我想适当地分配相应的大小.有没有一个函数可以这样做?
我的例子:

df <- data.frame(
  h = 0:23,
  x = c(22, 11, 5, 8 , 22, 88, 77, 7, 11, 5, 8 , 22, 88, 77, 11, 5, 8 , 22, 88, 77, 11, 5, 8 , 22))

ggplot() +
  geom_line(data = df, aes(h, x))

x列是数值。添加一刻钟后,我还想添加值 在原始小时之间,使图形平滑而不尖锐。怎么做,平均它,插值它?

kxe2p93d

kxe2p93d1#

由于不清楚 Dataframe 是如何构建的,因此这个答案是"暂定的":
数据:

df <- data.frame(
  h = 0:23,
  x = c(22, 11, 5, 8 , 22, 88, 77, 7, 11, 5, 8 , 22, 88, 77, 11, 5, 8 , 22, 88, 77, 11, 5, 8 , 22))

解决方案:

library(dplyr)
library(stringr)
df %>%
  data.frame(h = rep(df$h, each = 4),                             # quadruplicate rows
             x = rep(df$x, each = 4)) %>%                         # quadruplicate rows 
  mutate(h.1 = str_pad(h.1, width = 2, side = "left", pad = "0"), # add leading '0'
         qu = paste0(h.1, c(":00", ":15", ":30", ":45"))) %>%     # create quarters
  select( - c(h,x)) %>%                                           # deselect obsolete cols
  rename(c("h" = "h.1", "x" = "x.1"))                             # rename cols

结果:

h  x    qu
1  00 22 00:00
2  00 22 00:15
3  00 22 00:30
4  00 22 00:45
5  01 11 01:00
6  01 11 01:15
7  01 11 01:30
8  01 11 01:45
9  02  5 02:00
10 02  5 02:15
11 02  5 02:30
12 02  5 02:45
13 03  8 03:00
14 03  8 03:15
15 03  8 03:30
16 03  8 03:45
17 04 22 04:00
18 04 22 04:15
19 04 22 04:30
20 04 22 04:45
21 05 88 05:00
22 05 88 05:15
23 05 88 05:30
24 05 88 05:45
25 06 77 06:00
26 06 77 06:15
27 06 77 06:30
28 06 77 06:45
29 07  7 07:00
30 07  7 07:15
31 07  7 07:30
32 07  7 07:45
33 08 11 08:00
34 08 11 08:15
35 08 11 08:30
36 08 11 08:45
37 09  5 09:00
38 09  5 09:15
39 09  5 09:30
40 09  5 09:45
41 10  8 10:00
42 10  8 10:15
43 10  8 10:30
44 10  8 10:45
45 11 22 11:00
46 11 22 11:15
47 11 22 11:30
48 11 22 11:45
49 12 88 12:00
50 12 88 12:15
51 12 88 12:30
52 12 88 12:45
53 13 77 13:00
54 13 77 13:15
55 13 77 13:30
56 13 77 13:45
57 14 11 14:00
58 14 11 14:15
59 14 11 14:30
60 14 11 14:45
61 15  5 15:00
62 15  5 15:15
63 15  5 15:30
64 15  5 15:45
65 16  8 16:00
66 16  8 16:15
67 16  8 16:30
68 16  8 16:45
69 17 22 17:00
70 17 22 17:15
71 17 22 17:30
72 17 22 17:45
73 18 88 18:00
74 18 88 18:15
75 18 88 18:30
76 18 88 18:45
77 19 77 19:00
78 19 77 19:15
79 19 77 19:30
80 19 77 19:45
81 20 11 20:00
82 20 11 20:15
83 20 11 20:30
84 20 11 20:45
85 21  5 21:00
86 21  5 21:15
87 21  5 21:30
88 21  5 21:45
89 22  8 22:00
90 22  8 22:15
91 22  8 22:30
92 22  8 22:45
93 23 22 23:00
94 23 22 23:15
95 23 22 23:30
96 23 22 23:45

相关问题