2017-07-25 75 views
1

數據創建一個新的列:

structure(list(datetime = structure(c(6L, 2L, 4L, 5L, 1L, 3L), .Names = c("V1", 
"V2", "V3", "V4", "V5", "V6"), .Label = c(" 2016-12-01 00:00:30", 
" 2016-12-01 00:02:17", " 2016-12-01 00:06:17", " 2016-12-01 00:28:10", 
" 2016-12-01 01:17:02", "2016-12-01 00:00:00"), class = "factor")), .Names = "datetime", row.names = c("V1", 
"V2", "V3", "V4", "V5", "V6"), class = "data.frame") 

代碼使用摘要數據中的R

library(lubridate) 
library(dplyr) 

data$datetime <- ymd_hms(data$datetime) 
data <- dplyr::arrange(data, datetime) 
data$hour <- cut.POSIXt(data$datetime, "hour") 
data %>% group_by(hour) %>% summarize(count = n()) 

輸出 甲tibble:2×2 小時計數 1 2016-12 -01 00:00:00 5 2 2016-12-01 01:00:00 1

輸出在原始數據集 日期時間的小時 2016年12月1日00:00:00 00 2016年12月1日00:00:01 00

希望的輸出

DateTime  Hour Count 
       <fctr> <int> 
1 2016-12-01 00:00:00  5 
2 2016-12-01 01:00:00  1 

我想在每個小時顯示記錄數,並將這些數字放入一個稱爲count的新列中。希望你們能理解我的問題。 請幫我傢伙..

回答

0

的選項將是添加separate%>%

library(tidyr) 
res <- data %>% 
     group_by(hour) %>% 
     summarize(count = n()) %>% 
     separate(hour, into = c('DateTime', 'Hour'), sep=' ') 

group_by/summarize可以更改爲count

res <- count(data, hour) %>% 
      separate(hour, into = c('DateTime', 'Hour'), sep=' ') 
+0

這隻能說明在彙總R控制檯。它不會在我的數據集中使用計數值創建新列。怎麼做?? –

+1

哦,非常感謝你的朋友。乾杯!!! –