在R中使用sqldf联接数据

时间:2019-03-25 18:47:48

标签: r sqldf

我有一段代码:

sql_iv <- "select year, month, day, 
count(HR)
from y2
group by year, month, day
order by year, month, day"

y3=sqldf(sql_iv)

计算一天中进行一次测量的次数(每天变化的次数):

     Year Month Day count(HR)
1    2018   4    7    88
2    2018   4    8    327
3    2018   4    9    318
4    2018   4   10    274
5    2018   4   11    345
6    2018   4   12    275
.
.
.
189  2018  10   12    167

现在,我需要获取这些计算出的值,并将它们与数据进行合并,这些数据的每一项测量值都位于不同的行中(即,4月4日进行的所有测量值的最后一列都必须具有值88)。有人可以帮我吗?

前10次测量的数据结构(在48650中):

structure(list(Date = structure(c(1523119800, 1523119920, 1523119980, 
1523120280, 1523120340, 1523120400, 1523120460, 1523120520, 1523120580, 
1523120640), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
HR = c("97.0", "98.0", "95.0", "93.0", "94.0", "94.0", "92.0", 
"96.0", "89.0", "90.0"), Year = c(2018, 2018, 2018, 2018, 
2018, 2018, 2018, 2018, 2018, 2018), Month = c(4, 4, 4, 4, 
4, 4, 4, 4, 4, 4), Day = c(7, 7, 7, 7, 7, 7, 7, 7, 7, 7), 
Hour = c(16, 16, 16, 16, 16, 17, 17, 17, 17, 17), Minute = c(50, 
52, 53, 58, 59, 0, 1, 2, 3, 4)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

1 个答案:

答案 0 :(得分:0)

您在寻找这个吗?

library(dplyr)
mydata %>% 
  as_tibble() %>%
  left_join(sqldf %>% as_tibble, by = c("Year", "Month", "Day"))