繁体   English   中英

R:如何创建名称和值取决于参数的 function 对象,并且这些对象是在全局环境中找到的?

[英]R : How to create objects with a function which name and value depend on an argument, and that these objects are found in the global environment?

我有以下情况:我有不同的数据帧,我希望能够根据其中一列的值(log2FoldChange>1 和 logFoldChange<-1)为每个 dataframe 创建 2 个数据帧。

为此,我使用以下代码:

DJ29_T0_Overexpr = DJ29_T0[which(DJ29_T0$log2FoldChange > 1),]
DJ29_T0_Underexpr = DJ29_T0[which(DJ21_T0$log2FoldChange < -1),]

DJ229_T0 是我的 dataframe 之一。

第一个问题:未考虑 dataframe 的符号,其中 log2FoldChange < -1。

但主要问题是在制作function时,我写了以下内容:

spliteOverUnder <- function(res){
  nm <-deparse(substitute(res))
  assign(paste(nm,"_Overexpr", sep=""), res[which(as.numeric(as.character(res$log2FoldChange)) > 1),])
  assign(paste(nm,"_Underexpr", sep=""), res[which(as.numeric(as.character(res$log2FoldChange)) < -1),])
}

然后我跑了:

spliteOverUnder(DJ29_T0)

没有错误消息,但我的对象没有导出到我的全局环境中。 我尝试使用return(paste(nm,"_Overexpr", sep="")但它只返回 object 名称,但不返回关联的 dataframe。

使用paste()强制使用assign() ,所以我不能这样做:

spliteOverUnder <- function(res){
  nm <-deparse(substitute(res))
  paste(nm,"_Overexpr", sep="") <<- res[which(as.numeric(as.character(res$log2FoldChange)) > 1),]
  paste(nm,"_Underexpr", sep="") <<- res[which(as.numeric(as.character(res$log2FoldChange)) < -1),]
}

spliteOverUnder(DJ24_T0)

我遇到以下错误:

Error in paste(nm, "_Overexpr", sep = "") <<- res[which(as.numeric(as.character(res$log2FoldChange)) > : 
  could not find function "paste<-"

如果您以前遇到过这种困难,我将不胜感激。 如果你知道,一旦 function 工作,如何使用 For 循环遍历包含我所有数据帧的列表,将这个 function 应用于每个数据帧,我也是一个接受者。

谢谢

分配时,使用pos参数将新对象提升到 function 之外。

function(){
    assign(x = ..., value = ...,
           pos = 1 ## see below
    )
}

... 其中 0 = 函数的本地环境,1 =下一个环境(其中定义了 function)等。

编辑通用 function 以在您的全局环境中创建拆分数据框。 但是,您可能更愿意保存新的数据帧(从函数内部)或者只是将它们转发给下游函数,而不是用中间对象塞满您的工作区。

splitOverUnder <- function(the_name_of_the_frame){
    df <- get(the_name_of_the_frame)
    df$cat <- cut(df$log2FoldChange,
                  breaks = c(-Inf, -1, 1, Inf),
                  labels = c('underexpr', 'normal', 'overexpr')
                  )
    split_data <- split(df, df$cat)
    sapply(c('underexpr', 'overexpr'),
           function(n){
               new_df_name <- paste(the_name_of_the_frame, n, sep = '_')
               assign(x = new_df_name,
                      value = split_data$n,
                      envir = .GlobalEnv
                      )
           }
           )
}

## say, df1 and df2 are your initial dataframes to split:
sapply(c('df1', 'df2'), function(n) splitOverUnder(n))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM