编写函数:为什么 dplyr select() 可以使用带引号的列名,但 df$col_name 却不能?

问题描述 投票:0回答:1

我一直在阅读有关“整洁评估”的帖子和文档,但我的结果与我正在阅读的内容没有意义。我的职能是:

ttsplit = function(prepped_data, outcome_column){
  
  sample <- sample(c(TRUE, FALSE), nrow(prepped_data), replace=TRUE, prob=c(0.7,0.3))
  train  <- prepped_data[sample, ]
  test   <- prepped_data[!sample, ]
  
  Xtrain = train %>% 
    select(!outcome_column)
  
  ytrain = train$outcome_column
  
  Xtest = test %>% 
    select(!outcome_column)
  
  ytest = test$outcome_column
  
  return(list(Xtrain, ytrain, Xtest, ytest))
}

我的问题是:

  1. 我的理解是,在 select() 语句中,我需要使用

    {{outcome_column}}
    取消引用我的列名。然而,它照原样工作得很好。为什么?

  2. ytrain = train$outcome_column
    不起作用。列表中的第一项和第三项
    datasets
    是正确的,第二项和第四项是NULL。

datasets = ttsplit(model1data, "SalePrice")

Warning messages:
1: Unknown or uninitialised column: `outcome_column`. 
2: Unknown or uninitialised column: `outcome_column`. 

> datasets[2]
[[1]]
NULL

> datasets[4]
[[1]]
NULL

train${{outcome_column}}
无效,那么在这种情况下如何取消引用? (我当前的解决方案是使用 select() 语句,这很好,但我想理解。)

  1. 此外,如果我只是在函数之外运行
    df$'column_name'
    ,它就可以工作。为什么?
> model1data$'SalePrice'
   [1] 208500 181500 223500...

我的数据是这样的,但是列更多。

> model1data
# A tibble: 1,460 × 3
      Id LotArea SalePrice
   <dbl>   <dbl>     <dbl>
 1     1    8450    208500
 2     2    9600    181500
 3     3   11250    223500
 4     4    9550    140000
 5     5   14260    250000
 6     6   14115    143000
 7     7   10084    307000
 8     8   10382    200000
 9     9    6120    129900
10    10    7420    118000
# … with 1,450 more rows

这是 dput 版本:

structure(list(Id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), LotArea = c(8450, 
9600, 11250, 9550, 14260, 14115, 10084, 10382, 6120, 7420), SalePrice = c(208500, 
181500, 223500, 140000, 250000, 143000, 307000, 2e+05, 129900, 
118000)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))
r function dplyr quosure
1个回答
0
投票

在您的代码中,名为“outcome_column”的列和名为“SalesPrice”的列之间存在歧义,这里最好的做法是不要使用

{{ }}
,而是使用
one_of()

  1. 和4.

train$outcome_column
相当于
train$"outcome_column"
。这就是美元运算符的工作原理,
outcome_column
不被评估,但是你可以做
train[[outcome_column]]

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.