[英]R function to compare columns
In R language I would like to create a function to view selected columns for comparison in the Viewer. 在R语言中,我想创建一个函数来查看选定的列以便在Viewer中进行比较。 Assuming my dataframe is df1:
假设我的数据帧是df1:
compare_col <- function(x){
select(df1, x) %>%
View()
}
If I define the function by x, I can only put input 1 column. 如果我用x定义函数,我只能输入1列。
compare_col <- function(x)
compare_col("col_1")
Only if I define the function by say x,y, then can I input in 2 columns. 只有当我用x,y定义函数时,才可以输入2列。
compare_col <- function(x, y)
compare_col("col_1", "col_2")
How can I create a function that is dynamic enough to input in any no. 如何创建一个动态足以输入任何数字的函数。 of columns?
列?
You can use the rlang
package to achieve this. 您可以使用
rlang
包来实现此目的。 This will allow you to input a string of column names using the syms
and !!!
这将允许您使用
syms
输入一串列名称!!!
operator which will splice and evaluate in the given environment dynamically as you require. 运算符,它将根据您的需要动态地在给定环境中进行拼接和评估。
library(dplyr)
#library(rlang)
compare_col <- function(x){
df1 %>% select(!!! syms(x)) %>%
View()
}
compare_col(c("col1", "col2"))
刚刚意识到,我实际需要做的就是在调用函数时向量化输入。
compare_col(c("col1", "col2"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.