R函数使用传递的对象名+里面的另一个名字

时间:2017-01-10 00:03:15

标签: r

我想构建一个函数来调用另一个名称与主对象名相关的对象。

例如,Main对象是'VCU_Players',另一个对象是'VCU_Players_opp'

在我的函数中,我需要在计算中使用这两个对象。

所以我想做

my_function<- function(x) {
  y<-deparse(substitute(x))
  z<-"_opp"
  y<- paste(y,z,sep = "")

#My Calculations
x$newfield<- x$pts+ y$pts
Return(x)
}

现在我想将对象VCU_Players传递给函数

创建my_function(VCU_Players)

但该功能未计算VCU_Players_opp对象

1 个答案:

答案 0 :(得分:0)

考虑传递字符串文字并使用get()来检索相应的对象:

teams <- c("Team1", "Team2", "Team3", "Team4", "Team5", "Team6",
           "Team7", "Team8", "Team9", "Team10", "Team11", "Team12")

my_function <- function(i) {
  x <- get(paste0(i, "_players"))
  y <- get(paste0(i, "_opp"))

  # My Calculations
  x$newfield <- x$pts + y$pts    
  return(x)
}

dfList <- lapply(teams, my_function)

然而,理想情况下,使用许多对象的一些列表,而不是在全局环境中分离多个对象。尝试从您的数据源(即Excel)将多个对象导入单个列表:

teamdfs <- c(Team1_players, Team2_players, Team3_players, Team4_players, Team5_players, Team6_players,
             Team7_players, Team8_players, Team9_players, Team10_players, Team11_players, Team12_players)

team_oppdfs <- c(Team1_opp, Team2_opp, Team3_opp, Team4_opp, Team5_opp, Team6_opp,
                 Team7_opp, Team8_opp, Team9_opp, Team10_opp, Team11_opp, Team12_opp)

my_function <- function(x, y) {
  # My Calculations
  x$newfield <- x$pts + y$pts
  return(x)
}

dfList <- mapply(my_function, teamdfs, team_oppdfs, SIMPLIFY = FALSE)
          # EQUIVALENT TO Map(my_function, teamdfs, team_oppdfs)