English 中文(简体)
查阅档案名称和“来源”档案的途径
原标题:get filename and path of `source`d file
  • 时间:2012-01-12 12:56:12
  •  标签:
  • r
  • sweave

如何找到自己的途径?

Background:

I work a lot with .R scripts or .Rnw files. My projects are organized in a directory structure, but the path of the project s base directory frequently varies between different computers (e.g. because I just do parts of data analysis for someone else, and their directory structure is different from mine: I have projects base directories ~/Projects/StudentName/ or ~/Projects/Studentname/Projectname and most students who have just their one Project usually have it under ~/Measurements/ or ~/DataAnalysis/ or something the like - which wouldn t work for me).

因此,一线类似

    setwd (my.own.path ()) 

令人难以置信的有用性,因为它能够确保工作名录成为项目的基本道路,而不论项目实际在哪里。 用户不必考虑建立工作名录。

让我澄清: 我寻求一种解决办法,与编辑/IDE s代码<>source 或Sweave保持一致。 不可思议用户的关键短处。

最佳回答

Just FYI, knitr will setwd ( to the dir of the content file when (and only when) evaluation the Code chunks, i.e. if You打knit( path/to/input.) Rnw >,工作继承人将暂时改为path/to/。 如果你想要知道密码库中的输入 d,目前你可以称为无出口功能knitr:input_dir(。 (我今后可以出口)。

问题回答

从k3 s Seb的建议开始,这里的想法是:

  • the combination of username (login) and IP or name of the computer could be used to select the right directory.

这导致这样的情况:

    setwd (switch (paste (Sys.info () [c ("user", "nodename")], collapse="."), 
           user.laptop  = "~/Messungen",
           user2.server = "~/Projekte/Projekt/",
           ))

因此有一个自动解决办法,即:

  • works with source
  • works with Sweave
  • 即便是互动会议的工作,如果指挥系统按行各行各行,也可进行。

  • <>用户代码><>/代码>和nodename的组合当然需要具体确定。

  • the paths need to be edited by hand, though.

欢迎改进!


最新情况:

Gabor Grothendieck今天回答了有关救助问题:

this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)

<代码>来源


另一项更新: 现在,我从事的大多数数据分析工作。 科学研究院的项目基本上解决了这一问题:科学研究院每当我转换项目时,将工作指南修改为项目根基目录。

因此,我可以把项目目录按我的愿望(如果学生想要的话,他们也可以放下复印件)和数据文档和文字/<代码提要。 Rnws through edition control (We use a private git services). RStudio项目文档被置于版本控制范围之外,即.gitignore。 <代码>。 Rproj.user。

Obviously, within the project, the directory structure needs to be synchronized.

You can use sys.calls() to get the command used to source the file. Then you need a bit of trickery using regular expressions to get the pathname, bearing in mind that source("something/filename") could have used either the absolute or relative path. Here s a first attempt at putting all the pieces together: try inserting the following lines at the top of a source file.

whereFrom=sys.calls()[[1]]
# This should be an expression that looks something like
# source("pathname/myfilename.R")
whereFrom=as.character(whereFrom[2]) # get the pathname/filename
whereFrom=paste(getwd(),whereFrom,sep="/") # prefix it with the current working directory
pathnameIndex=gregexpr(".*/",whereFrom) # we want the string up to the final  / 
pathnameLength=attr(pathnameIndex[[1]],"match.length")
whereFrom=substr(whereFrom,1,pathnameLength-1)
print(whereFrom) # or "setwd(whereFrom)" to set the working directory

它并不十分有力——例如,它将在窗户上失败<条码>(姓名/名称),而且如果你有一卷档案,就会对情况进行测试——但你可能能够在其中找到解决办法。

我没有直接的解决办法,如何获得档案目录,但如果你拥有范围有限的目录和目录结构,你可能会使用。

 if(file.exists("c:/somedir")==TRUE){setwd("c:/somedir")}

你可以检查有关目录的格局,然后确定继承人。 这是否有助于你?

还有一个问题是,工作名录是一个全球性的变量,可以用任何文字加以改动,这样,如果你的文字打上另一个文字,它就不得不放弃。 在《科学学会一》中,“和”使用课程; 编制工作指南――和; 来源文件所在地(我知道,它不理想),然后我的文字确实。

wd = getwd ()
...
source ("mySubDir/myOtherScript.R", chdir=TRUE); setwd (wd)
...
source ("anotherSubDir/anotherScript.R", chdir=TRUE); setwd (wd)

这样,就可以维持一套工作名录。 我很想知道,这用的是语言本身。

这一回答涉及<代码>源,也载于<代码>nvim-R——如果与<代码>knitr<>/code>和类似材料一起工作,我没有任何想法。 任何反馈都受到赞赏。

If you have multiple scripts source-ing each other, it is important to get the correct one. That is, the largest i for which sys.frame(i)$ofile exists.

get.full.path.to.this.sourced.script = function() {    
    for(i in sys.nframe():1) {  # Go through all the call frames,
                                # in *reverse* order.
        x = sys.frame(i)$ofile
        if(!is.null(x))               # if $ofile exists,
            return(normalizePath(x))  #  then return the full absolute path
    }
}




相关问题
How to plot fitted model over observed time series

This is a really really simple question to which I seem to be entirely unable to get a solution. I would like to do a scatter plot of an observed time series in R, and over this I want to plot the ...

REvolution for R

since the latest Ubuntu release (karmic koala), I noticed that the internal R package advertises on start-up the REvolution package. It seems to be a library collection for high-performance matrix ...

R - capturing elements of R output into text files

I am trying to run an analysis by invoking R through the command line as follows: R --no-save < SampleProgram.R > SampleProgram.opt For example, consider the simple R program below: mydata =...

R statistical package: wrapping GOFrame objects

I m trying to generate GOFrame objects to generate a gene ontology mapping in R for unsupported organisms (see http://www.bioconductor.org/packages/release/bioc/vignettes/GOstats/inst/doc/...

Changing the order of dodged bars in ggplot2 barplot

I have a dataframe df.all and I m plotting it in a bar plot with ggplot2 using the code below. I d like to make it so that the order of the dodged bars is flipped. That is, so that the bars labeled "...

Strange error when using sparse matrices and glmnet

I m getting a weird error when training a glmnet regression. invalid class "dgCMatrix" object: length(Dimnames[[2]]) must match Dim[2] It only happens occasionally, and perhaps only under larger ...

Generating non-duplicate combination pairs in R

Sorry for the non-descriptive title but I don t know whether there s a word for what I m trying to achieve. Let s assume that I have a list of names of different classes like c( 1 , 2 , 3 , 4 ) ...

Per panel smoothing in ggplot2

I m plotting a group of curves, using facet in ggplot2. I d like to have a smoother applied to plots where there are enough points to smooth, but not on plots with very few points. In particular I d ...

热门标签