PyPer User
PyPer User

Reputation: 259

Converting argument to partial string

I'm sure this is pretty basic, but I haven't been able to find an answer on stackoverflow.

The basics of what I'm working with is

f1 <- function(x) {
setwd("~/Rdir/x")
col1 <- f2(...)
col2 <- f3(...)
genelist <- data.frame(co1,col2)
write.csv(genelist, file="x.csv")
}

Essentially what I want is for x to be replaced by whatever I input for example f1(test) would save a file called test.csv into the directory Rdir/test.

I would post a more complete code sample of what i'm working with - but it is very long.

Upvotes: 1

Views: 39

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81713

You can create the filename with paste0 and the path with file.path:

x <- "test"
file.path("~/Rdir", x, paste0(x, ".csv"))
# "~/Rdir/test/test.csv"

Upvotes: 2

user1981275
user1981275

Reputation: 13372

You can use ?paste:

setwd(paste("~/Rdir/", x, sep=""));

and

write.csv(genelist, file=paste(x, ".csv", sep=""))

in your example. However, it might me more straightforward not to change the working directory but instead just to specify the full path when saving:

write.csv(genelist, file=paste("~/Rdir/", x, "/", x, ".csv", sep=""))

but be aware that this will crash if the directory does not exist. You could have a look at ?dir.create to create the directory first, in case it does not exist.

Upvotes: 3

Related Questions