簡體   English   中英

在 r 中查找每 3 列或具有 NA 的數據的平均值

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

我想使用下面可用的數據計算每第 8 列的平均值。 數據有 6 列,其中包含信息,然后是數據列。 我已經在這個平台上尋找了其他可用的代碼,例如“如何在 R 中平均每 3 列 NA”,但它們沒有 NA,也沒有在數據列之前有多個信息列。

"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.

嘗試這個:

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

其中df是數據框

測試用例:

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM