R-Project Filepath from Concatenation

R-project filepath from concatenation

getmonitor <- function(id, directory=getwd(), ...){

csvfile <- sprintf("%03d.csv", id)

filepath <- file.path(directory, csvfile)

foo <- read.csv(filepath, ...)

foo

}

Function to concatenate paths?

Yes, file.path()

R> file.path("usr", "local", "lib")
[1] "usr/local/lib"
R>

There is also the equally useful system.path() for files in a package:

R> system.file("extdata", "date_time_zonespec.csv", package="RcppBDT")
[1] "/usr/local/lib/R/site-library/RcppBDT/extdata/date_time_zonespec.csv"
R>

which will get the file extdata/date_time_zonespec.csv irrespective of

  1. where the package is installed, and
  2. the OS

which is very handy. Lastly, there is also

R> .Platform$file.sep
[1] "/"
R>

if you insist on doing it manually.

Issue with VBA file path concatenating

Found the problem, I was using a package in R, which required R Studio to be open. The original file path works.

Function for constructing relative paths in R?

Similar, but shorter:

make.path.relative = function(base, target) {
common = sub('^([^|]*)[^|]*(?:\\|\\1[^|]*)$', '^\\1/?', paste0(base, '|', target))

paste0(gsub('[^/]+/?', '../', sub(common, '', base)),
sub(common, '', target))
}

make.path.relative('C:/home/adam', 'C:/home/adam/tmp/R')
#[1] "tmp/R"

make.path.relative('/home/adam/tmp', '/home/adam/Documents/R')
#[1] "../Documents/R"

make.path.relative('/home/adam/Documents/R/Project', '/home/adam/minetest')
#[1] "../../../minetest"

Voodoo regex comes from here.

R-project error message - cannot read table

You are passing the function csvfile as the file argument, not the string that that function returns when called. You want

foo <- read.csv(csvfile(id))

Use variable in file path in R

Use file.path:

dir <- file.path("some", "path")
bla <- file.path("some", "directory")
files <- c("file1.R", "file2.exe")

file.path(dir, bla, files)

Produces:

[1] "some/path/some/directory/file1.R"   "some/path/some/directory/file2.exe"

You could also use paste to generically concatenate strings, but file.path makes sure the correct directory separators are used for your OS, etc.

Concatenating file with path to get full path in C

You shouldn't modify argv[i]. Even if you do, you only have one argv[1], so doing strcat() on it is going to keep appending to whatever you had in it earlier.

You have another subtle bug. A directory name and file names in it should be separated by the path separator, / on most systems. You don't add that in your code.

To fix this, outside of your while loop:

size_t arglen = strlen(argv[1]);

You should do this in your while loop:

/* + 2 because of the '/' and the terminating 0 */
char *fullpath = malloc(arglen + strlen(ep->d_name) + 2);
if (fullpath == NULL) { /* deal with error and exit */ }
sprintf(fullpath, "%s/%s", path, ep->d_name);
/* use fullpath */
free(fullpath);


Related Topics



Leave a reply



Submit