簡體   English   中英

創建一個使用字符串和變量調用列的函數 - 使用基數 R 和 dplyr

[英]Creating a function that calls a column both using a string and as a variable - use of base R and dplyr

我需要一些幫助來理解評估在我正在編寫的函數中是如何工作的:

該函數將執行兩個涉及列“id”的操作,其名稱由用戶提供,其中包括一些省略的內容:

possible_matches <- function(i, df, id){
  
  k1 <- df$j[df$id == df$id[i]]
  df3 <-  df%>%
    mutate(index = {{id}})
  
  list(df3, k1)
}

如您所見,這將使用兩種不同的方式來調用id - 是否有一種簡單的方法來統一這兩種方法? 起初,我嘗試在第一部分寫一些東西在df[, 'id'] == df[i, 'id] ,但這會給出一個錯誤,說不可能比較大小不等的數據幀。

下面是一個例子:

df <- data.frame(V1 = c(1:5, 2:6),
                 j = 1:10)


possible_matches(2, df, V1)

給我:

[[1]]
   V1  j index
1   1  1     1
2   2  2     2
3   3  3     3
4   4  4     4
5   5  5     5
6   2  6     2
7   3  7     3
8   4  8     4
9   5  9     5
10  6 10     6

[[2]]
integer(0)

這顯然是錯誤的,因為至少有一行的V1值等於 do df$V1[2]

如果id是一個不帶引號的列名

possible_matches <- function(i, df, id) {
     
     # // convert the id to string with `as_name` after converting to quosure
     idnew <- rlang::as_name(rlang::enquo(id))
     # // now we use [[ to subset the column and then specify the i index
     k1 <- df$j[df[[idnew]] == df[[idnew]][i]]
      df3 <-  df%>%
         mutate(index = {{id}}) # // curly-curly for quosure + evaluation (!!)

       list(df3, k1)
   }
    

-測試

possible_matches(2, df, V1)
#[[1]]
#   V1  j index
#1   1  1     1
#2   2  2     2
#3   3  3     3
#4   4  4     4
#5   5  5     5
#6   2  6     2
#7   3  7     3
#8   4  8     4
#9   5  9     5
#10  6 10     6

#[[2]]    
#[1] 2 6

如果我們想使用filter

possible_matches <- function(i, df, id) {            
        to_filter <- df%>% 
                      # // select the column
                      select({{id}}) %>% 
                      # // slice the row
                      slice(i) %>%
                      # // pull the column as vector
                      pull(1)
         k1 <- df %>% 
                   # // now we filter with the value from to_filter
                   filter({{id}} == to_filter) %>%
                   pull(j)
            df3 <-  df%>%
                mutate(index = {{id}})
       
              list(df3, k1)
         
         
       
      }
possible_matches(2, df, V1)
#[[1]]
#   V1  j index
#1   1  1     1
#2   2  2     2
#3   3  3     3
#4   4  4     4
#5   5  5     5
#6   2  6     2
#7   3  7     3
#8   4  8     4
#9   5  9     5
#10  6 10     6

#[[2]]
#[1] 2 6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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