简体   繁体   中英

Find average for every 3 columns or data with NAs in r

I want to calculate the means for every 8th column using data available below. The data has 6 columns which contain information followed by data columns. I have looked for other codes available on this platform eg 'How to average every 3 columns with NA in R' but they dont have NAs nor do they have more than one information columns before data columns.

"I", "J"), DOB = c("25/11/2020", "29/4/2021", "29/1/2021", "24/10/2020", 
"24/10/2020", "10/2/2021", "16/10/2020", "16/10/2020", "28/3/2021", 
"8/6/2020"), DOG = c("3/5/2021", "28/11/2021", "27/8/2021", "17/5/2021", 
"19/6/2021", "25/9/2021", "5/5/2021", "12/3/2021", "22/9/2021", 
"8/12/2020"), REL = c(159L, 213L, 210L, 205L, 238L, 227L, 201L, 
147L, 178L, 183L), GRP = c("tyn", "tyn", "tyn", "ged", "ged", 
"ged", "buun", "buun", "bunn", "buun"), DOS = c(NA, NA, NA, NA, 
NA, NA, "30.5.2021", NA, NA, "25.3.2021"), M1 = c(42L, 0L, 38L, 
0L, 0L, 46L, 34L, 44L, 39L, 35L), M2 = c(0L, 45L, 42L, 34L, 39L, 
0L, 50L, 42L, 0L, NA), M3 = c(34L, 50L, 53L, 0L, 45L, 42L, 53L, 
0L, 45L, NA), M4 = c(42L, 0L, 34L, 34L, 50L, 53L, 0L, 34L, 50L, 
NA), M5 = c(0L, 45L, 50L, 42L, 0L, 34L, 34L, 42L, 0L, NA), M6 = c(38L, 
42L, 53L, 0L, 45L, 50L, NA, 0L, 45L, NA), M7 = c(0L, 34L, 0L, 
34L, 50L, 53L, NA, 34L, 50L, NA), M8 = c(0L, 39L, 0L, 42L, 0L, 
34L, NA, 34L, 42L, NA), M9 = c(NA, 0L, 0L, 0L, 45L, 50L, NA, 
50L, 0L, NA), M10 = c(NA, 27L, 0L, NA, 0L, 0L, NA, 53L, 34L, 
NA)), class = "data.frame", row.names = c(NA, -10L))```

The problem is brought by the presents of NAs and columns which contain information before the data columns.

try this:

library(dplyr)
df[,seq_len(ncol(df)) %% 8 == 0] %>% apply(MARGIN = 2, FUN = mean, na.rm = TRUE)

Where df is a data frame

TEST CASE:

d2 <- as.data.frame(matrix(1:100, ncol = 20))

d2[,1:6] <- stringi::stri_rand_strings(n = 1, length = 4)

d2[4,16] <- NA
d2[3,8] <- NA

df <- d2
df[,seq_len(ncol(df)) %% 8 == 0] %>% apply(MARGIN = 2, FUN = mean, na.rm = TRUE)

#> V8   V16 
#> 38.00 77.75 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM