我缺乏理解的是,使用下面的示例,我認為:
df2 <- df1 %>% left_join(code_label, by = c("team"="code"))
并且,在一個函式中,
df2 <- df1 %>% left_join(code_label, by = c(x='code'))
將被相同地評估但它們不是,有沒有辦法包裝 'x' 所以它們是?
df1_id <- c(1, 2, 3, 4, 5, 6)
team <- c(1, 2, 1, 6, 4, 1)
year <- c(2014, 2014, 2009, 2020, 2015, 2017)
df1 <- data.frame(df1_id, team, year)
code_id <- c(1,2,3,4,5,6)
code <- c(1,2,3,4,5,6)
label <- c("team_A", "team_B","team_C","team_D","team_E","team_F")
code_label <- data.frame(code_id, code,label)
df2 <- df1 %>% left_join(code_label, by = c("team"="code"))
給出了一個結果。但我想將 df1 的列名“team”作為一個未命名的物件(我認為是正確的描述?)傳遞給一個函式,如下所示:
f_show_labels_with_codes(x = "team")
f_show_labels_with_codes <- function(x)
{
print(x)
df2 <- df1 %>% left_join(code_label, by = c(x='code'))
}
但它會產生一個錯誤:
Error: Join columns must be present in data.
x Problem with `x`
我查看了圍繞 enquo 等的檔案,這對我來說是新的。但是在函式中 print(x) 已經回傳 [1] "team"。這個問題看起來很相似,但我認為并不完全相同。
uj5u.com熱心網友回復:
我們可以使用命名向量 setNames
f_show_labels_with_codes <- function(x) {
print(x)
df1 %>%
left_join(code_label, by = setNames('code', x))
}
-測驗
> f_show_labels_with_codes(x = "team")
[1] "team"
df1_id team year code_id label
1 1 1 2014 1 team_A
2 2 2 2014 2 team_B
3 3 1 2009 1 team_A
4 4 6 2020 6 team_F
5 5 4 2015 4 team_D
6 6 1 2017 1 team_A
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383112.html
下一篇:將一些資料序列分成幾個相鄰的部分
