【问题标题】:R: How to pass a name of DataFrame to a function, if a name is created by functionR:如果名称是由函数创建的,如何将 DataFrame 的名称传递给函数
【发布时间】:2018-06-28 07:47:31
【问题描述】:

我有一个例子,在 gWidgets 的 gdfedit 函数中创建了一个数据框,但名称不固定(根据另一个向量更改)。我想将此数据帧传递给另一个函数,但我不知道如何。

我的代码有点复杂,但这个例子总结了我的问题:

 example <- function(df1, df2){
   df1$v3 <- df2$v1
 }

 x <- "01"
 df1 <- data.frame(v1=c(1,2,3), v2=c(6,7,8))
 gdfedit(items= df1, name=paste("df", x, sep = '' ), container = gwindow() , expand=TRUE)

 example(df1, paste("df", x, sep = '' )) #this obviously doesn't work. 

我可以用 for() 和 if() 循环遍历“x”的向量,但我想要更优雅的解决方案。有任何想法吗?

【问题讨论】:

    标签: r function-call


    【解决方案1】:

    您需要在将数据帧传递给您的函数时调用get

    library(gWidgetsRGtk2)
    library(RGtk2Extras)
    
    #your defined function
    example <- function(x1, x2, x1_col, x2_col){
      x1[, x1_col] <- x2[, x2_col]
      return(x1)
    }
    
    #sample data
    x <- "01"
    df1 <- data.frame(v1 = c(1,2,3), v2 = c(6,7,8))
    
    #edit dataframe and save it as a new dataframe
    gdfedit(items = df1, name = paste0("df", x), container = gwindow(), expand = T)
    
    #call function
    example(df1, get(paste0("df", x)), "new_column", "v1")
    

    给出(如果我将df1 '原样'保存在df01 中)

      v1 v2 new_column
    1  1  6          1
    2  2  7          2
    3  3  8          3
    

    注意:我稍微修改了你的函数定义)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-30
      • 2020-10-01
      • 2017-07-21
      • 2014-02-07
      • 2022-01-11
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      相关资源
      最近更新 更多