【问题标题】:How to refer to a tibble column, using a variable name, in a pipe (R)如何在管道 (R) 中使用变量名引用 tibble 列
【发布时间】:2017-08-08 13:31:57
【问题描述】:

我对 R 很陌生,所以这个问题可能有点幼稚。

我有一个包含几列的小标题,我想通过对 N 个 bin 中的一个列中的值进行分箱来创建一个因子 (Bin)。这是在管道中完成的。但是,我希望能够在脚本顶部定义要分箱的列(例如 bin2use = RT),因为我希望这很灵活。

我尝试了几种使用此变量引用列名的方法,但我无法让它工作。其中我尝试过 get()、eval()、[[]]

简化示例代码

Subject <- c(rep(1,100), rep(2,100))
RT <- runif(200, 300, 800 )
data_st <- tibble(Subject, RT)

bin2use = 'RT'
nbin = 5

binned_data <- data_st %>%
  group_by(Subject) %>%
  mutate(
    Bin = cut_number(get(bin2use), nbin, label = F)
  )

Error in mutate_impl(.data, dots) : 
  non-numeric argument to binary operator

【问题讨论】:

  • 请展示一个可重现的例子,即data_st
  • 对不起,应该立即这样做。它现在在那里。

标签: r variables pipe refer


【解决方案1】:

我们可以使用 `lazyeval 进行非标准评估

library(dplyr)
library(ggplot2)
f1 <- function(colName, bin){
     call <- lazyeval::interp(~cut_number(a, b, label = FALSE),
                        a = as.name(colName), b = bin)
     data_st %>%
           group_by(Subject) %>% 
           mutate_(.dots = setNames(list(call), "Bin"))
} 

f1(bin2use, nbin)
#Source: local data frame [200 x 3]
#Groups: Subject [2]

#   Subject       RT   Bin
#     <dbl>    <dbl> <int>
#1        1 752.2066     5
#2        1 353.0410     1
#3        1 676.5617     4
#4        1 493.0052     2
#5        1 532.2157     3
#6        1 467.5940     2
#7        1 791.6643     5
#8        1 333.1583     1
#9        1 342.5786     1
#10       1 637.8601     4
# ... with 190 more rows

【讨论】:

  • 太棒了!谢谢!
猜你喜欢
  • 2021-12-18
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多