在R函数中传递参数

时间:2019-11-20 08:02:30

标签: r function arguments match

我正在尝试编写一个小的函数来匹配两个组。在每对中,两组的ab值具有相同的值,而在c中最接近。

df <- structure(
  list(group = c(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1),
       a = c(2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 1),
       b = c(1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0),
       c = c(0.13, 0.64, 0.34, 0.36, 0.3, 0.81, 0.83, 0.98, 0.13, 0.36, 0.51, 0.26, 0.64, 0.43)),
  class = "data.frame", row.names = c(NA, -14L))

pairit <- function(data, case, id) {
   A = df[which(df$group == 1), ]
   B = df[which(df$group == 0), ]
   A$id = c(1:nrow(A))
   B$id = NA
   for (i in 1:nrow(A)) {
      B$TMP <- (B$a == A$a[i] & B$b == A$b[i] & is.na(B$id))
      B$dif = abs(B$c - A$c[i])
      B <- B[order(-B$TMP, B$dif),]
     if (B$TMP[1]) B$id[1] = A$id[i]
   }
   B <- B[!names(B) %in% c("TMP", "dif")]
   new_df <- rbind(A, B)
   colnames(new_df)[colnames(new_df)=="id"] <- paste0(id)
   return(new_df)
}

# The following worked, but I directly entered augments into the function   

pairit(data = df, case="group == 1", id="pid")

它没有将参数data = dfcase = "group == 1"传递给函数,因为我直接将这些参数输入了函数A = df[which(df$group == 1), ]B = df[which(df$group == 0), ]。我尝试使用paste0(data, "$", case)eval(paste0(data, "$", case))之类的东西来替换df$group == 1,但没有成功。任何建议和解释将不胜感激。

0 个答案:

没有答案