[英]Calculate mean based on first part of row.name() in R
我有一個看起來像這樣的數據框:
structure(list(value1 = c(1, 2, 3, 4, 5), value2 = c(1, 2, 2,
2, 2), value3 = c(1, 1, 2, 3, 4)), class = "data.frame", row.names = c("apple1",
"apple2", "orange1", "orange2", "plum"))
價值1 | 價值2 | 價值3 | |
---|---|---|---|
蘋果1 | 1 | 1 | 1 |
蘋果2 | 2 | 2 | 1 |
橙色1 | 3 | 2 | 2 |
橙色2 | 4 | 2 | 3 |
李子 | 5 | 2 | 4 |
現在我想根據行名的第一部分在每一列上運行平均值 function (例如,我想獨立於他們的蘋果編號計算蘋果組的 value1 的平均值。)我發現像這樣的東西有效:
y<-x[grep("apple",row.names(x)),]
mean(y$value1)
mean(y$value2)
mean(y$vvalue3)
y<-x[grep("orange",row.names(x)),]
mean(y$value1)
mean(y$value2)
mean(y$value2)
y<-x[grep("plum",row.names(x)),]
mean(y$value1)
mean(y$value2)
mean(y$value2)
但是對於更大的數據集,這將需要很長時間,所以我想知道是否有一種更有效的方法可以根據行名的第一部分對數據進行子集化,然后計算平均值。
使用tidyverse
:
library(tidyverse)
df %>%
tibble::rownames_to_column("row") %>%
dplyr::mutate(row = str_remove(row, "\\d+")) %>%
dplyr::group_by(row) %>%
dplyr::summarize(across(where(is.numeric), ~ mean(.), .groups = "drop"))
在基礎R
,您可以執行以下操作:
df$row <- gsub("\\d+", "", rownames(df))
data.frame(do.call(cbind, lapply(df[,1:3], function(x) by(x, df$row, mean))))
Output
row value1 value2 value3
* <chr> <dbl> <dbl> <dbl>
1 apple 1.5 1.5 1
2 orange 3.5 2 2.5
3 plum 5 2 4
數據
df <- structure(list(value1 = 1:5, value2 = c(1, 2, 2, 2, 2), value3 = c(1,
1, 2, 3, 4)), class = "data.frame", row.names = c("apple1", "apple2",
"orange1", "orange2", "plum"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.