[英]Computing dot product between rows in dataframes in list and a vector in R
我想獲得列表中每行數據幀和向量之間的內點積; 列表中有數據框的位置(因此數據框應在列表中單獨保存)。 我可以在使用減法時做到這一點,但不能在點積時做到這一點。 請參閱下面的示例代碼。
#Example data
V1 <- c(1, 2)
V2 <- c(3, 4)
V3 <- c(5, 6)
df1 <- tibble(V1, V2, V3)
V1 <- c(7, 8, 9)
V2 <- c(10, 11, 12)
V3 <- c(13, 14, 15)
df2 <- tibble(V1, V2, V3)
df_list <- list(df1, df2)
df_list
vector <- c(2, 2, 2)
df_list_subtract <- df_list %>%
map(~ map2_df(.x, vector, `-`))
df_list_subtract
# Does not work
df_list_dotproduct <- df_list %>%
map(~ map2_df(.x, vector, `%*%`))
df_list_dotproduct
# Does not work
df_list_dot_product <- df_list %>%
map(~ map2_df(.x, rep(vector, each = x), `%*%`))
df_list_dot_product
提前致謝
tidyverse
在逐行操作中並不是很好。
這是一個基本的 R 方式:
lapply(df_list, function(x) apply(x, 1, `%*%`, vector))
#[[1]]
#[1] 18 24
#[[2]]
#[1] 60 66 72
或使用tidyverse
library(purrr)
df_list %>% map(~pmap_dbl(., ~c(...) %*% vector))
您得到的錯誤是因為矩陣不符合,這意味着您只能執行 mxn %*% nx(something)。 因此,您只需要將 data.frame 轉換為矩陣,因此它是 3x(something) 並且應該沒問題:
你不需要 map2,除非你有另一列可以相乘,但我在這里看不到它:
df_list %>% map(~as.matrix(.x) %*% vector)
[[1]]
[,1]
[1,] 18
[2,] 24
[[2]]
[,1]
[1,] 60
[2,] 66
[3,] 72
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.