我正在嘗試在函式中使用 pivot_wider。但是,一旦更改格式,我就無法訪問新列。我收到列 a 和 b 不存在的錯誤訊息。
這是我的功能:
dip <- function(df, a, b, year_min) {
wow <- df %>%
filter(country %in% c("a","b")) %>%
filter(date >= year_min) %>%
group_by(rcid) %>%
pivot_wider(id_cols = "rcid",
names_from = c("a","b"),
values_from = "vote") %>%
na.omit()
percentage <- sum(wow$a == wow$b)*100/nrow(wow_df)
return(percentage)
}
dip(joined_df, "United States", "Germany", 1990-01-01)
當我嘗試在沒有該功能的情況下運行代碼時,它可以作業:
joined_df <- un_votes %>%
inner_join(un_roll_calls, by = "rcid")
wow_df <- joined_df %>%
filter(country == "United States" | country == "Germany") %>%
filter(date >= "1990-01-01") %>%
group_by(rcid) %>%
pivot_wider(id_cols = "rcid",
names_from = country,
values_from = "vote") %>%
na.omit()
percentage <- sum(wow_df$"Germany" == wow_df$"United States")*100/nrow(wow_df)
我是相當新的功能和欣賞任何提示。我使用的資料來自 un_votes 包。
這是我收到的錯誤訊息:
錯誤
chr_as_locations():!不能對不存在的列進行子集化。? 列a不存在。回溯:
- 全球傾角(joined_df,“美國”,“德國”,1990 - 1 - 1)
- tidyr:::pivot_wider.data.frame(...)
- tidyr::build_wider_spec(...)
- tidyselect::eval_select(enquo(names_from), 資料)
- tidyselect:::eval_select_impl(...) ...
- tidyselect:::reduce_sels(node, data_mask, context_mask, init = init)
- tidyselect:::walk_data_tree(new, data_mask, context_mask)
- tidyselect:::as_indices_sel_impl(...)
- tidyselect:::as_indices_impl(x, vars, call = call, strict = strict)
- tidyselect:::chr_as_locations(x, vars, call = call) chr_as_locations 中的錯誤(x, vars, call = call)
uj5u.com熱心網友回復:
這里我們需要取消參考"a", "b"。另外,替換$為[[
dip <- function(df, a, b, year_min) {
wow <- df %>%
filter(country %in% c(a, b)) %>%
filter(date >= as.Date(year_min)) %>%
pivot_wider(id_cols = "rcid",
names_from = country,
values_from = "vote") %>%
na.omit()
percentage <- sum(wow[[a]] == wow[[b]])*100/nrow(wow)
return(percentage)
}
-測驗
dip(joined_df, "United States", "Germany", "1990-01-01")
[1] 33.33333
資料
joined_df <- structure(list(rcid = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L), country = c("United States", "United States",
"United States", "United States", "United States", "Germany",
"Germany", "Germany", "Germany", "Germany", "Spain", "Spain",
"Spain", "Spain", "Spain"), date = structure(c(12904, 8066, -25932,
8401, 12843, 11231, 6971, 10470, 9251, 13787, 14304, 14396, 13361,
11566, 8126), class = "Date"), vote = c(73, 88, 25, 73, 76, 73,
91, 25, 88, 31, 45, 34, 80, 66, 60)), row.names = c(NA, -15L),
class = "data.frame")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512631.html
標籤:r功能枢
