我想计算的平均柱x和y下面,并添加一列Mean,
> z
w x y
1 5 1 1
2 6 2 2
3 7 3 3
4 8 4 0
Run Code Online (Sandbox Code Playgroud)
我使用的代码如下:
z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何忽略最后一个y值中的 0 ;该行x和y值的平均值仅为 4。
所需的输出:
> 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
Run Code Online (Sandbox Code Playgroud)
我们可以replace的0到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
Run Code Online (Sandbox Code Playgroud)
或使用 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, .)
Run Code Online (Sandbox Code Playgroud)
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"))
Run Code Online (Sandbox Code Playgroud)