In R language I would like to create a function to view selected columns for comparison in the Viewer. Assuming my dataframe is df1:
compare_col <- function(x){
select(df1, x) %>%
View()
}
If I define the function by x, I can only put input 1 column.
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.
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. This will allow you to input a string of column names using the syms
and !!!
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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.