簡體   English   中英

R函數比較列

[英]R function to compare columns

在R語言中,我想創建一個函數來查看選定的列以便在Viewer中進行比較。 假設我的數據幀是df1:

compare_col <- function(x){
  select(df1, x) %>%
    View()
}

如果我用x定義函數,我只能輸入1列。

compare_col <- function(x)

compare_col("col_1")

只有當我用x,y定義函數時,才可以輸入2列。

compare_col <- function(x, y)

compare_col("col_1", "col_2")

如何創建一個動態足以輸入任何數字的函數 列?

您可以使用rlang包來實現此目的。 這將允許您使用syms輸入一串列名稱!!! 運算符,它將根據您的需要動態地在給定環境中進行拼接和評估。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM