这是我的数据:https://gofile.io/?c=7WLqCD
看起来是这样的:
head(testframe)
Time Station1 Station2 Station3 Station4
01.01.2017 07:00 27 38 26 25
01.01.2017 14:00 22 49 25 16
01.01.2017 21:00 41 53 46 36
02.01.2017 07:00 22 38 26 19
02.01.2017 14:00 20 54 35 13
02.01.2017 21:00 36 45 30 26
我想要计算每天站1到站4的平均值,也就是第1-3行、第4-6行、第7-9行等等。
class (testframe$Station1)
是factor
,我知道它必须是数值才能计算平均值。所以我试着把它变成这样:
testframe[,4] = as.numeric(as.character(testframe$Station4))
这不管用。我缺少标记为#的值。我用NA代替了它们,但是3号站和4号站仍然有问题。
另外,这个计算平均值的代码不起作用。它给了我错误的结果。
colMeans(matrix(testframe$Station1, nrow=3))
发布于 2019-05-07 15:36:43
也许你需要这样的东西
library(dplyr)
df %>%
group_by(group = gl(n()/3, 3)) %>%
summarise_at(-1, mean, na.rm = TRUE)
# group Station1 Station2 Station3 Station4
# <fct> <dbl> <dbl> <dbl> <dbl>
#1 1 30 46.7 32.3 25.7
#2 2 26 45.7 30.3 19.3
发布于 2019-05-07 15:18:55
编辑:OP更改后:使用dplyr
df %>%
rename(Date=row.names) %>%
group_by(Date) %>%
summarise_at(vars(contains("S")),list(Mean=mean))
# A tibble: 2 x 5
Date Station1_Mean Station2_Mean Station3_Mean Station4_Mean
<chr> <dbl> <dbl> <dbl> <dbl>
1 01.01.2017 30 46.7 32.3 25.7
2 02.01.2017 26 45.7 30.3 19.3
数据:
df<-read.table(text=" Time Station1 Station2 Station3 Station4
01.01.2017 07:00 27 38 26 25
01.01.2017 14:00 22 49 25 16
01.01.2017 21:00 41 53 46 36
02.01.2017 07:00 22 38 26 19
02.01.2017 14:00 20 54 35 13
02.01.2017 21:00 36 45 30 26",header=T,
as.is=T,fill=T,row.names = NULL)
原始答案:(每3行取平均值)
我们可以执行以下操作(我已经过滤以删除非数字):
colMeans(df[seq(0,nrow(df),3),-c(1,2)])
Station1 Station2 Station3 Station4
38.5 49.0 38.0 31.0
数据:
df<-structure(list(row.names = c("01.01.2017", "01.01.2017", "01.01.2017",
"02.01.2017", "02.01.2017", "02.01.2017"), Time = c("07:00",
"14:00", "21:00", "07:00", "14:00", "21:00"), Station1 = c(27L,
22L, 41L, 22L, 20L, 36L), Station2 = c(38L, 49L, 53L, 38L, 54L,
45L), Station3 = c(26L, 25L, 46L, 26L, 35L, 30L), Station4 = c(25L,
16L, 36L, 19L, 13L, 26L)), class = "data.frame", row.names = c(NA,
-6L))
https://stackoverflow.com/questions/56025680
复制相似问题