r-按行计算平均时间



我试图计算数据帧中每行的平均时间,并将结果放在一列中的另一个daaframe中,只与平均时间保持一致,但对于每一行,我都会得到相同的结果。

我的dafaframe(df(:

X      X2015.01.01    X2015.01.02       X2015.01.05        X2015.01.06
<time>      <time>         <time>             <time>           <time>
NA secs     NA secs    7.702222 hours   7.578889 hours  8.056667 hours  
NA secs     NA secs    6.682778 hours   6.664722 hours  6.567500 hours  
NA secs     NA secs    6.738056 hours   6.054722 hours  6.621667 hours  
NA secs     NA secs    9.473611 hours   NA hours        9.573889 hours  

我尝试过的:

df_2 <- data.frame(matrix(nrow=nrow(df)))
for (i in 1:ncol(df)) {
df_2$i<- mean(df[,i],na.rm = TRUE)
}
df_2
matrix.nrow...nrow.df.. mean
<lgl>                  <time>
NA                      7.708015 hours              
NA                      7.708015 hours          
NA                      7.708015 hours  

df

df <- data.frame(structure(list(
X = 
structure(c(NA_real_, NA_real_, NA_real_, NA_real_), 
class = "difftime", 
units = "secs"), 

X2015.01.01 =
structure(c(NA_real_, NA_real_, NA_real_, NA_real_), 
class = "difftime",
units = "secs"), 
X2015.01.02 = 
structure(c(7.20833333333333, 8.10916666666667, 
6.6925, 7.33833333333333),
class = "difftime", 
units = "hours"), 

X2015.01.03 = 
structure(c(7.578889, 6.664722, 
6.054722 , NA_real_),
class = "difftime", 
units = "hours"),
X2015.01.04 = 
structure(c(8.056667 , 6.567500 , 
6.621667  , 9.573889 ),
class = "difftime", 
units = "hours")
)))

将列转换为lubridate中可用的duration有助于计算:

df %>%
mutate(across(everything(), ~ as.duration(.x))) %>%
mutate(totalDuration = rowSums(.[1:5], na.rm = TRUE),
avgDurationSecs = totalDuration / 5,
avgDurationHours = dhours(avgDurationSecs / (60*60))) %>%
glimpse()

您还可以使用dhours等获得更多单位

我发现我可以简单地将时间转换为数字,然后使用rowMeans

for (i in 1:ncol(df)){
df[i]<-lapply(df[i], as.numeric)
}
df$avg<-rowMeans(df,na.rm=TRUE)

如果你想把它放在另一个数据帧中。

df_2 <- data.frame(df$avg)

相关内容

  • 没有找到相关文章

最新更新