Scott Davidson Scott Davidson - 6 days ago 6
R Question

Importing a file only if it has been modified since last import and then save to a new object

I am trying to create a script that I run about once a week. The goal is that it will go out and check an MS Excel file that a co-worker manages. It then tests to see if the date the file was modified is newer then the last time it was imported. If it is newer, it will import the file (I am using readxl package - WONDERFUL!) into a new object that is a named with the date the original Excel file was last modified included in the object name. I have everything working except for the assignment of the imported data.frame to a new object that includes the date.

An example of the code I am using is:

First I create an object with a path pointing to the file of interest.

pfdFilePath <- file.path("H:", "3700", "3780", "002-00", "3.
Project Information", "Program", "RAH program.xls")


after testing to verify the file has been modified, I have tried simple assignment ("test" is just an example for simplification):

paste("df-", as.Date(file.info(pfdFilePath)$mtime), sep = "") <- "test"


But that code produces an error:


Error in paste("df-", as.Date(file.info(pfdFilePath)$mtime), sep = "") <- "test" :
target of assignment expands to non-language object


I then try the assign function:

assign(paste("df-", as.Date(file.info(pfdFilePath)$mtime), sep = ""), "test")


Running this code creates an object that looks to be okay, but when I evaluate it, or try using str() or class() I get the following error:


Error in df -
df-2016-08-09
:
non-numeric argument to binary operator


I am pretty sure this is an error that has to do with the environment I am using assign, but being relatively new to R, I cannot figure it out. I understand that the assign function seems to be frowned upon, but those warnings seem to centered on for-loops vs. lapply functions. I am not really iterating within a function though. Just a dynamically named object whenever I run a script. I can't come up with a better way to do it. If there is another way to do this that doesn't require the assign function, or a better way to use assign function , I would love to know it.

Thank you in advance, and sorry if this is a duplicate. I have spent the entire evening digging and can't derive what I need.

Answer

Abdou provided the key.

assign(paste0("df.", "pfd.", strftime(file.info(pfdFilePath)$mtime, "%Y%m%d")), "test01")

I also converted to the cleaner paste0 function and got rid of the dashes to avoid confusion. Lesson learned.

Works perfectly.

Comments