2017-04-20 15 views
0

我有一個數據幀,看起來像這樣:彙總多個病人每名患者每天平均基於時間的數據中的R

id    time value 
01 2014-02-26 13:00:00  6 
02 2014-02-26 15:00:00  6 
01 2014-02-26 18:00:00  6 
04 2014-02-26 21:00:00  7 
02 2014-02-27 09:00:00  6 
03 2014-02-27 12:00:00  6 

數據幀由一個情緒得分在不同時間的郵票在整個多的一天耐心。

我想數據框變成這個樣子:

id 2014-02-26 2014-02-27 
01  6.25  4.32 
02  5.39  8.12 
03  9.23  3.18 
04  5.76  3.95 

隨着各行的耐心,每個列的數據幀的所有日子的日平均值。如果患者在特定日期沒有情緒分數,我希望該值爲NA。

什麼是這樣做的使用像ddply功能,或從其他包的最簡單的方法?


df <- structure(list(id = c(1L, 2L, 1L, 4L, 2L, 3L), time = structure(c(1393437600, 
1393444800, 1393455600, 1393466400, 1393509600, 1393520400), class = c("POSIXct", 
"POSIXt"), tzone = ""), value = c(6L, 6L, 6L, 7L, 6L, 6L)), .Names = c("id", 
"time", "value"), row.names = c(NA, -6L), class = "data.frame") 
+1

你是如何得到這些值的?例如6.25的id 01 – Sotos

+0

我已經彌補了這個值,所以他們不是實際的日均值。 –

回答

0

在基礎R,你可以用reshape這樣的結合aggregate

# get means by id-date 
temp <- setNames(aggregate(value ~ id + format(time, "%y-%m-%d"), data=df, FUN=mean), 
       c("id", "time", "value")) 
# reshape to get dates as columns 
reshape(temp, direction="wide", idvar="id", timevar="time") 
    id value.14-02-26 value.14-02-27 
1 1    6    NA 
2 2    6    6 
3 4    7    NA 
5 3    NA    6 
2

根據您的描述,這似乎是你需要什麼,

library(tidyverse) 

df1 %>% 
    group_by(id, time1 = format(time, '%Y-%m-%d')) %>% 
    summarise(new = mean(value)) %>% 
    spread(time1, new) 

#Source: local data frame [4 x 3] 
#Groups: id [4] 

#  id `2014-02-26` `2014-02-27` 
#* <int>  <dbl>  <dbl> 
#1  1   6   NA 
#2  2   6   6 
#3  3   NA   6 
#4  4   7   NA 
0

我會reccomend使用data.table包,然後方法是非常相似的索托斯tidiverse解決方案。

library(data.table) 

df <- data.table(df) 

df[, time1 := format(time, '%Y-%m-%d')] 

aggregated <- df[, list(meanvalue = mean(value)), by=c("id", "time1")] 
aggregated <- dcast.data.table(aggregated, id~time1, value.var="meanvalue") 

aggregated 
# id 2014-02-26 2014-02-27 
# 1: 1   6   NA 
# 2: 2   6   6 
# 3: 3   NA   6 
# 4: 4   NA   7 

(我覺得我的結果不同的話,因爲我的系統運行在另一個時區,我進口datetime對象爲UTC)