【问题标题】:Saving the output of a function as a new dataf.frame and using the name of the original input in the saving name将函数的输出保存为新的 dataf.frame 并在保存名称中使用原始输入的名称
【发布时间】:2020-04-22 10:06:14
【问题描述】:

我编写了一个函数,它根据排名从列表中获取前 50 个结果。

myfunction <- function(x){

...selects the top 50 results

return(the top 50 results)

如果您需要确切的功能,我可以添加更多细节。

理想情况下,我希望函数执行的操作是将前 50 个列表保存为新的 data.frame,方法是自动包含输入的名称,如下所示:

'x'_top_50

所以我可以重复使用该功能,它会自动保存输出以供以后使用。

任何帮助都会很棒,谢谢!

编辑

这是我从第一个答案中得到的:

t50<-function(x){
m101mb<-x[,1:2]
m101ts<-x[,3:4]
incommon<-intersect(m101mb$mb_gs,m101ts$ts_gs)
df1<-m101mb[m101mb$mb_gs %in% incommon,]
df2<-m101ts[m101ts$ts_gs %in% incommon,]
df3<-df1[order(df1$mb_gs),]
df4<-df2[order(df2$ts_gs),]
df5<-cbind(df3,df4)
df6<-data.frame(df5$mb_rank,df5$ts_rank)
df7<-rowMeans(df6)
df8<-data.frame(df5,df7)
df9<-data.frame(df8$ts_gs,df8$df7)
df10<-df9[order(df9$df8.df7),]
colnames(df10)<-c("Gene_symbol","Gene_rank")
assign(paste(deparse(substitute(x)),"top", "50", sep = "_"), df10[1:50,])
return(df10[1:50,])
}

但它仍然不会保存为新变量。

谢谢。

【问题讨论】:

    标签: r function dataframe save output


    【解决方案1】:

    我相信您想要的是函数assign() 为数据框分配特定名称;和deparse()subsitute() 提取先前给定的变量名称。

    myfunction <- function(x){
    
      #whatever you're doing it's here that results in the_top_50_results as a dataframe
    
      assign(paste(deparse(substitute(x)), "top", "50", sep = "_"), the_top_50_results, envir = .GlobalEnv)
    }
    

    【讨论】:

    • 您好,感谢您的快速回复!我想我理解代码的逻辑,但不太确定如何在函数中实现它。我将添加并编辑我原来的问题,向您展示我的意思。
    • 添加了envir 参数以确保将变量分配给全局环境。我忘了添加,它使数据框分配在函数范围内,而不是全局范围内。我希望这能解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多