Reputation: 902
I would like to calculate the below data frame mean. Due to the NA's,
I receive the following message: Warning message:In mean.default(df_new) : argument is not numeric or logical: returning NA. Is there a way to bypass this error?
Data structure:
Desire output rule =AVERAGE(B2:P7)
Sample data:
structure(list(X1 = c(1, 2, 3, 4, 5, 6), `10` = c(10, 10, 10,
10, NA, NA), `20` = c(20, 20, 20, NA, NA, NA), `30` = c(30, 30,
30, 30, NA, NA), `40` = c(40, 40, 40, 40, NA, NA), `50` = c(50,
50, 50, 50, 50, 50), `60` = c(60, 60, NA, NA, NA, NA), `70` = c(70,
70, NA, NA, NA, NA), `80` = c(80, 80, NA, NA, NA, NA), `90` = c(90,
90, NA, NA, NA, NA), `100` = c(NA, NA, NA, NA, NA, NA), `110` = c(110,
110, 110, NA, NA, NA), `120` = c(120, 120, NA, NA, NA, NA), `130` = c(NA,
NA, NA, NA, NA, NA), `140` = c(NA, NA, NA, NA, NA, NA), `150` = c(150,
NA, NA, NA, NA, NA), X17 = c(NA, NA, NA, NA, "average", "57.14285714"
)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L), spec = structure(list(cols = list(X1 = structure(list(), class = c("collector_double",
"collector")), `10` = structure(list(), class = c("collector_double",
"collector")), `20` = structure(list(), class = c("collector_double",
"collector")), `30` = structure(list(), class = c("collector_double",
"collector")), `40` = structure(list(), class = c("collector_double",
"collector")), `50` = structure(list(), class = c("collector_double",
"collector")), `60` = structure(list(), class = c("collector_double",
"collector")), `70` = structure(list(), class = c("collector_double",
"collector")), `80` = structure(list(), class = c("collector_double",
"collector")), `90` = structure(list(), class = c("collector_double",
"collector")), `100` = structure(list(), class = c("collector_logical",
"collector")), `110` = structure(list(), class = c("collector_double",
"collector")), `120` = structure(list(), class = c("collector_double",
"collector")), `130` = structure(list(), class = c("collector_logical",
"collector")), `140` = structure(list(), class = c("collector_logical",
"collector")), `150` = structure(list(), class = c("collector_double",
"collector")), X17 = structure(list(), class = c("collector_character",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
Upvotes: 1
Views: 56
Reputation: 887223
We may need rowMeans
rowMeans(df_new[grep("^\\d+$", names(df_new))], na.rm = TRUE)
Or if it is for the whole dataset, unlist
the data.frame
by selecting only the columns of interest to create a vector
mean(unlist(df_new[grep("^\\d+$", names(df_new))]), na.rm = TRUE)
[1] 57.14286
Or in a tidy way
library(dplyr)
df_new %>%
select(matches('^\\d+$')) %>%
as.matrix %>%
mean(na.rm = TRUE)
#[1] 57.14286
Upvotes: 1