armipunk armipunk - 3 months ago 41
R Question

How to modify i in an R loop?

I have several large R objects saved as .RData files: "this.RData", "that.RData", "andTheOther.RData" and so on. I don't have enough memory, so I want to load each in a loop, extract some rows, and unload it. However, once I load(i), I need to strip the ".RData" part of (i) before I can do anything with objects "this", "that", "andTheOther". I want to do the opposite of what is described in How to iterate over file names in a R script? How can I do that? Thx

Edit: I omitted to mention the files are not in the working directory and have a filepath as well. I came across Getting filename without extension in R and file_path_sans_ext takes out the extension but the rest of the path is still there.


Do you mean something like this?

i <- c("/path/to/this.RDat", "/another/path/to/that.RDat")
f <- gsub(".*/([^/]+)", "\\1", i)
f1 <- gsub("\\.RDat", "", f)
[1] "this" "that"

On windows' paths you have to use "\\" instead of "/"

Edit: Explanation. Technically, these are called "regular expressions" (regexps), not "patterns".

  • . any character

  • .* arbitrary number (including 0) of any kind of characters

  • .*/ arbitrary number of any kind of characters, followed by a /

  • [^/] any character but not /

  • [^/]+ arbitrary number (1 or more) of any kind of characters, but not /

  • ( and ) enclose groups. You can use the groups when replacing as \\1, \\2 etc.

So, look for any kind of character, followed by /, followed by anything but not the path separator. Replace this with the "anything but not separator".

There are many good tutorials for regexps, just look for it.