我正在做一個專案,我需要找到在 3 維空間中測量的一系列行為與 3 維空間中預先確定的點之間的距離。我撰寫了一個函式來計算點與單個行為之間的距離,當我僅將其應用于一個行為時,該函式有效。但是,我需要將其應用于更大資料框中的約 750 種行為。因此,我希望逐項嵌套較大的行為資料幀,然后使用 map_dbl 將該函式應用于這些嵌套資料幀中的每一個。但是,我不斷收到錯誤訊息:
錯誤:mutate()列有問題distance。? distance = map_dbl(data, calc_distance_from_beh). x 連接列必須存在于資料中。x 問題dim。? 錯誤發生在第 1 行。
當 map_dbl 被應用于無法訪問“dim”列以加入的嵌套資料幀時,似乎發生了一些事情,我不知道為什么。
我在下面包含了一個只有兩種行為的可重現示例。
可重現的例子:
behaviors <- tibble(term = rep(c("abandon", "abet"), each = 3),
estimate = c(-3.31, -0.08, -0.11, 0.03, 0.34, -0.18),
dim = c("E", "P", "A", "E", "P", "A"))
optimal_behavior <- tibble(actor = "civil_engineer",
object = "civil_engineer",
opt_beh = c(1.905645, 0.9960085, -0.17772678),
dim = c("E", "P", "A"))
calc_distance_from_beh <- function(nested_df){
optimal_behavior <- as_tibble(optimal_behavior)
nested_df <- as_tibble(nested_df)
df_for_calculations <- left_join(optimal_behavior, nested_df, by = "dim")
df_for_calculations %>%
mutate(dist = (estimate-opt_beh)^2) %>%
summarise(total_dist = sum(dist)) %>%
pull()
}
behaviors_distance <- behaviors %>%
nest_by(term) %>%
mutate(distance = map_dbl(data, calc_distance_from_beh))
uj5u.com熱心網友回復:
如果 'value' 列被命名為estimate,就ungroup在nest_by(因為nest_by創建了一個rowwise阻止map訪問每個元素的屬性)
library(purrr)
library(dplyr)
behaviors %>%
nest_by(term) %>%
ungroup %>%
mutate(distance = map_dbl(data, calc_distance_from_beh))
# A tibble: 2 × 3
term data distance
<chr> <list<tibble[,2]>> <dbl>
1 abandon [3 × 2] 28.4
2 abet [3 × 2] 3.95
或代替map,我們可以直接應用功能mutate,因為它是rowwise
behaviors %>%
nest_by(term) %>%
mutate(distance = calc_distance_from_beh(data)) %>%
ungroup
-輸出
# A tibble: 2 × 3
term data distance
<chr> <list<tibble[,2]>> <dbl>
1 abandon [3 × 2] 28.4
2 abet [3 × 2] 3.95
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327607.html
