我需要將資料框中的值(基于特定分組)乘以一個單獨的矩陣,該矩陣對這些值施加某種權重。乘法是我撰寫的函式的一部分。我知道如何以最基本的方式做到這一點。但我無法理解如何在更現實的環境中做到這一點。我希望我的例子能說明這個問題。
我有以下示例資料集:
set.seed(45)
tibble(site = rep(c(LETTERS[1:3]), each = 6),
name = rep(c(letters[10:15]), 3),
size = runif(18)) %>%
arrange(site, name) -> d_tibble
我還有一個可以代表某種權重的矩陣:
d_matrix <- matrix(0, 6, 6)
diag(d_matrix) <- 1
rownames(d_matrix) <- letters[10:15]
colnames(d_matrix) <- letters[10:15]
d_matrix
## j k l m n o
## j 1 0 0 0 0 0
## k 0 1 0 0 0 0
## l 0 0 1 0 0 0
## m 0 0 0 1 0 0
## n 0 0 0 0 1 0
## o 0 0 0 0 0 1
我還有一個函式應該將向量乘以p矩陣b
test_fct <- function(a, b) {
p <- a / sum(a)
sum(p * (p %*% b))
}
然后我想做這樣的事情,即使用我的函式summarise():
#d_tibble %>%
# group_by(site) %>%
# summarise(y = test_fct(size, b))
但我不知道如何b將矩陣(即矩陣)放入我的自定義函式中,以便它的列名在按 .name分組時與變數匹配site。
我嘗試的一種方法是將矩陣合并到資料框中 - 這樣我就可以將所有內容都放在一個資料框中:
d_tibble %>%
left_join(d_matrix %>%
as_tibble() %>%
mutate(name = colnames(d_matrix))) -> tibble_matrix_join
比我擁有所有這些但我需要以某種方式訪問name??給定site分組的變數的唯一值,以便為我的函式中的向量/矩陣乘法選擇正確的列(j、k、l、m、n、o)test_fct():
#tibble_matrix_join %>%
# group_by(site) %>%
# summarise(result = test_fct(size, b))
我試圖檢查一般設定是否有效,即僅適用于一個站點并包括矩陣中的所有名稱,它確實:
d_tibble %>%
filter(site == "A") %>%
pull(size) -> my_x
test_fct(my_x, d_matrix)
## [1] 0.1858158
my_p <- my_x/sum(my_x)
sum(my_p * (my_p %*% d_matrix))
## [1] 0.1858158
uj5u.com熱心網友回復:
對于該示例,d_matrix 中的所有列都可以在所有“站點”的 tibble 的“名稱”列中找到。如果不是這樣,我們可以這樣做
library(dplyr)
d_tibble %>%
group_by(site) %>%
summarise(out = test_fct(size, d_matrix[intersect(row.names(d_matrix),
name), intersect(colnames(d_matrix),
name), drop = FALSE]), .groups = "drop")
-輸出
# A tibble: 3 × 2
site out
<chr> <dbl>
1 A 0.186
2 B 0.264
3 C 0.218
- 測驗較小的資料
d_tibble %>%
slice_sample(n = 12) %>%
arrange(site, name) %>%
group_by(site) %>%
summarise(out = test_fct(size, d_matrix[intersect(row.names(d_matrix),
name), intersect(colnames(d_matrix),
name), drop = FALSE]), .groups = "drop")
-輸出
# A tibble: 3 × 2
site out
<chr> <dbl>
1 A 0.227
2 B 0.416
3 C 0.481
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/530791.html
標籤:rdplyr
