将一组可行的R命令封装到一个函数中的问题 [英] issues of wrapping up a set of workable R commands into a function

查看:168
本文介绍了将一组可行的R命令封装到一个函数中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用r命令集合生成一个dendrogam。它工作得很好,并将生成的dendromgram保存为PDF文件。为了提高效率,我将这些命令封装为一个函数,它不会改变任何内容。但是,pdf只是一个没有任何图形内容的空白文件。请让我知道我的函数定义有什么问题。
$ b

  myplot< -function(inputcsv,outputfile){

library(ggdendro)

library(ggplot2)

x <-read.csv(inputcsv,header = TRUE)

d <-as.dist(x,diag = FALSE,upper = FALSE)

hc< -hclust(d,ave)

dhc< -as.dendrogram(hc)

ddata< -dendro_data(dhc,type =rectangle)

ddata $ labels $ text< - gsub(\\\。,,ddata $ labels $ text)

ggplot(segment(ddata))+ geom_segment(aes(x = x0,y = y0,xend = x1,yend = y1))
pdf(outputfile,width = 30,height = 35 )

last_plot()

dev.off()
}


解决方案

R FAQ



将ggplot调用包装在print >

ggplot和朋友返回一个对象,并且绘图仅在打印对象时发生。当您在命令行上执行此操作时,将自动进行打印。当你把它放在一个脚本或函数中时,你必须自己做。



关于这是一个好主意还是一个愚蠢的东西,只是产生这样的问题继续......

I generate a dendrogam using a collection of r commands. It worked just fine and saved the generated dendromgram into a PDF file. To improve efficiency, I wrapped these commands as a function, which does not change anything. However, the pdf is just a blank file without any graphical content. Please let me know what’s wrong with my function defintion. Thanks.

myplot<-function(inputcsv, outputfile){

library(ggdendro)

library(ggplot2)

x<-read.csv(inputcsv,header=TRUE)

d<-as.dist(x,diag=FALSE,upper=FALSE)

hc<-hclust(d,"ave")

dhc<-as.dendrogram(hc)

ddata<-dendro_data(dhc,type="rectangle")

ddata$labels$text <- gsub("\\."," ",ddata$labels$text)

ggplot(segment(ddata))+geom_segment(aes(x=x0,y=y0,xend=x1,yend=y1))
pdf(outputfile, width=30,height=35)

last_plot()

dev.off()
}

解决方案

R FAQ

Wrap your ggplot call in a print() function.

ggplot and friends return an object, and the plotting only happens when the object is printed. When you do this on the command line the printing happens automatically. When you stick it in a script or function you have to do it yourself.

The debate on whether this is a good idea or a dumb thing that just generates questions like this continues...

这篇关于将一组可行的R命令封装到一个函数中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆