[英]Calculating rowMean ignoring 0 values
我想如下計算列x
和y
的平均值並添加一列Mean
,
> z
w x y
1 5 1 1
2 6 2 2
3 7 3 3
4 8 4 0
我正在使用如下代碼:
z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
但我不知道如何忽略最后一個y
值中的 0; 該行的x
和y
值的平均值僅為 4。
Output 需要:
> z
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 0 4
我們可以將0
replace
為NA
,然后用na.rm
可以忽略它
subz <- z[, c('x', 'y')]
z$Mean <- rowMeans(replace(subz, subz == 0, NA), na.rm = TRUE)
z
# w x y Mean
#1 5 1 1 1
#2 6 2 2 2
#3 7 3 3 3
#4 8 4 0 4
或使用dplyr
library(dplyr)
z %>%
# // replace the 0s to NA for the columns x, y
mutate(across(x:y, na_if, 0)) %>% # // => 0 -> NA
# // get the row means of columns x,y
transmute(z = select(., x:y) %>%
rowMeans(na.rm = TRUE)) %>%
# // bind with original dataset
bind_cols(z, .)
z <- structure(list(w = 5:8, x = 1:4, y = c(1L, 2L, 3L, 0L)),
class = "data.frame", row.names = c("1",
"2", "3", "4"))
另一種選擇:
z$Mean <- apply(z[c('x','y')], MARGIN=1, FUN=function(x) mean(x[x!=0]))
apply(., 1, mean)
的效率略低於rowMeans
,但更靈活。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.