使用R计算带有空白的数据框的平均值

Calculating a mean from a data frame with blanks with R

我有一个在不同位置有空白的数据框。我想计算行的平均值,但我不知道如何根据行使 n 灵活。

所有列的行数都相同。

均值 = sum/n

df1 <- data.frame(col1 = c(5, 9, NA, -0.9, -0.74, , 1.19, , -1, -0.4, 1.38, -1.5, 1, 0.64), 
                  col2 = c(4, 2, -9, 4, 19, 31, 4, -8, -15,NA,NA,NA,NA,NA),
                  col3 = c(1, -2, 5, 1.1, 33, 2, 7, 1, 1, 16, -22, - 2, -3,-10))

因此,对于第 1 行:

5+4+1 = 9/3 = 3

但对于第 3 行: (-9) + 5 = -4/2 = -2

非常感谢您的帮助!

试试这个:

 df1 <- data.frame(col1 = as.numeric(c(5, 9, NA, -0.9, -0.74, NA , 1.19, 2 , -1, -0.4, 1.38, -1.5, 1, 0.64)), 
                  col2 = as.numeric(c(4, 2, -9, 4, 19, 31, 4, -8, -15,NA,NA,NA,NA,NA)),
                  col3 = as.numeric(c(1, -2, 5, 1.1, 33, 2, 7, 1, 1, 16, -22, -2, -3,-10)))

 rowMeans(df1, na.rm=TRUE)

有可能,尽管您的数据是数字,R 将它们作为字符读入。

如果您的数据中有空白,即使它看起来是数字,也会将您的数据转换为字符。将它们转换为 NA,将列转换为数字,然后取平均值。

df[df == ''] <- NA
df[] <- lapply(df, as.numeric)
df$rowMean <- rowMeans(df, na.rm = TRUE)