簡體   English   中英

如何從選定的列計算行平均值

[英]How to calculate row mean from selected columns

我有一個看起來像這樣的 dataframe:

data <- as.data.frame(cbind('01-01-2018' = c(1.2,3.1,0.7,-0.3,2.0), '02-01-2018' = c(-0.1, 2.4, 4.9,-3.3,-2.7), '03-01-2018' = c(3.4, -2.6, -1.8, 0.1, 0.3)))

  01-01-2018  02-01-2018  03-01-2018
1      1.2       -0.1        3.4
2      3.1        2.4       -2.6
3      0.7        4.9       -1.8
4     -0.3       -3.3        0.1
5      2.0       -2.7        0.3

我想計算行均值僅考慮超過總行均值的列。

data$mn <- apply(data, 1, mean) 

  01-01-2018 02-01-2018 03-01-2018         mn
1        1.2       -0.1        3.4  1.5000000
2        3.1        2.4       -2.6  0.9666667
3        0.7        4.9       -1.8  1.2666667
4       -0.3       -3.3        0.1 -1.1666667
5        2.0       -2.7        0.3 -0.1333333

換句話說,對於每一行,我想計算超過data$mn的值的平均值。

我的最后一次嘗試是:

data$mintensity <- apply(data, 1, function(x) mean(x[x > data$mn]) ) 

但它沒有成功。

在計算它們的平均值之前,只需通過它們在各自行w中的平均值對每一行進行子集化。

w <- c("01-01-2018", "02-01-2018", "03-01-2018")  ## define columns

apply(data[, w], 1, function(x) mean(x[x > mean(x)]))
# [1]  3.40  2.75  4.90 -0.10  1.15

另一種方法是在計算rowMeans之前用NA's replace不超過行均值的數據點。 這大約快 30 倍

rowMeans(replace(data, data <= rowMeans(data[, w]), NA), na.rm=TRUE)
# [1]  3.40  2.75  4.90 -0.10  1.15

數據:

data <- structure(list(`01-01-2018` = c(1.2, 3.1, 0.7, -0.3, 2), `02-01-2018` = c(-0.1, 
2.4, 4.9, -3.3, -2.7), `03-01-2018` = c(3.4, -2.6, -1.8, 0.1, 
0.3)), class = "data.frame", row.names = c(NA, -5L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM