I have a file that I would to write away in a certain dir. Therefore I have the following code:
function <- {
file_path_new <- file.path("C:", "Users", "MavanderPeet", "Documents", "data")
setwd(file_path_new)
now <- Sys.time()
file_name <- paste0(now, "data_set.csv")
write.csv(data_frame, file_name)
# write.csv(data_frame, "file.csv") #for checking purposes
}
The part where I want to create a name with timestamp does not seem to work however... When I uncomment the line
write.csv(data_frame, "file.csv")
Everything works fine. So I guess it should be a syntax error....
Any thoughts??
The colon (:) is not allowed in Windows file names (reference).
Use a different format:
paste0(format(now, "%Y%m%d_%H%M%S_"), "data_set.csv")
In the answer by #Roland, now needs parenthesis:
paste0(format(now(), "%Y%m%d_%H%M%S_"), "data_set.csv")
Related
eem_import_dir is supposed to "Reads Rdata and RDa files with one eemlist each. The eemlists are combined into one and returned." However, in my case, only one file is read at the time, and thus no combination is happening...
I don't expect any error in the function which is part of the staRdom package. I guess my limited R knowledge limits my understanding of the function and what could be wrong.
All files are the same class (eemlist) and in the same format. Tried changing the folder, filenames, etc. Can someone please help me understand the requirements of the function? Why is only one file read at the time and not all combined?
function (dir)
{
eem_files <- dir(dir, pattern = ".RData$|.RDa$", ignore.case = TRUE) %>%
paste0(dir, "/", .)
for (file in eem_files) {
file <- load(file)
if (get(file) %>% class() == "eemlist") {
if (exists("eem_list"))
eem_list <- eem_bind(eem_list, get(file))
else eem_list <- get(file)
}
else {
warning(paste0(file, " is no object of class eemlist!"))
}
NULL
}
eem_list
}
I am trying to do text mining in Chinese with R.
In my data set, I have a column with people's comment like "连锁店购买的". And I have 2 other columns that I created thanks to JiebaR. These hold the segmented message ("连锁店", "购买", "的") and the keywords from these messages ("连锁店", "购买"). The keyword selection removes "不"("no" in Chinese) so I am trying to fetch it back from the words and add it to the keywords. Simple, right ?
To have a clean code, I put all my functions in a separate file and source it in my main file. And NOW something VERY weird happens : the function works when it's in the main file but doesn't work when it's in the file that I source ! (I just copied and pasted the function from my main to the "function" file and run the source(...) line...).
fetchingNeg <- function(df){
for (i in 1:nrow(df)){
if ("不" %in% unlist(df[i,]$words)){
df[i,]$keywords <- list(append(unlist(df[i,]$keywords),"不"))
}
}
return(df)
}
So I found the error : Encoding !
There was a character c that I knew was "不" but when I was doing print("不" == c) it would give FALSE... "不" is not encoded in UTF-8 in this case, so to make my code work I had to change it to
fetchingNeg <- function(df){
for (i in 1:nrow(df)){
# "不" is "\u{4e0d}" in UTF-8
if ("\u{4e0d}" %in% unlist(df[i,]$words)){
df[i,]$keywords <- list(append(unlist(df[i,]$keywords),"\u{4e0d}"))
}
}
return(df)
}
I am writing output to a file but the data is not appending. It is creating the last row each time. The code is as follows
op <- function(crime) {
filename <- paste(crime,".txt")
fileconn <- file(filename)
cat(nthecrime, file=fileconn, sep=" ",append=TRUE)
#write(nthecrime,file=fileconn, ncolumns=9, append=TRUE,sep="\t")
close(fileconn)
}
Both cat & write create a new file each time I call the above lines instead of appending. What am I missing?
Regards
Ganesh
From the ?cat help:
append logical. Only used if the argument file is the name of file
(and not a connection or "|cmd"). If TRUE output will be appended to
file; otherwise, it will overwrite the contents of file.
You should use filename, not fileconn. Try
cat(nthecrime, file=filename, sep=" ",append=TRUE)
Since I'm working with many subdirectories, I find setwd() pretty inconvient, as it demands from me to remember what are the current and previous location and change them back every time I perform different analysis. Things get more complicated when some paths need to be relative and other absolute.
I'm looking for a convenient way to apply the change for the specific fraction of code, as in Ruby:
Dir.chdir("newDir") do
# some code here #
end
I've written such ugly functions:
path = list()
tempDirNew <- function(..., abs= FALSE){
path$tempDir$old <<- getwd()
mod = ifelse(abs == TRUE,
'',
path$tempDir$old)
path$tempDir$new <<- file.path(mod, ...)
dir.create(path= path$tempDir$new, showWarnings= FALSE)
setwd(dir= file.path(path$tempDir$new))
}
tempDirOld <- function(){
setwd(dir= path$tempDir$old)
path$tempDir$new <- NULL
path$tempDir$old <- NULL
}
and apply tempDirNew('newdir') before and tempDirOld() after each part of the code.
But maybe there is some built-in, convenient way?
You might like that setwd returns the previous directory, so that you can do something like this in your functions:
f <- function(){
old <- setwd( "some/where" )
on.exit( setwd(old) )
# do something
}
This way, you don't mess with global variables, <<- etc ...
Why not just store your starting directory as a variable when you start and use it to reset your directory:
mydir <- getwd()
# do anything
# change directories
# do more stuff
# change directories
# yadda yadda yadda
setwd(mydir)
Also it sounds like you might want to leverage relative paths:
setwd('./subdir')
# do stuff, then go back:
setwd('../')
I want to save the my tab delim files manually. I mean that I want user to choose the directory and file name when he wants to save the data. (For an example I have merged individual files into single file and want to save it.)
Usually I use write.table but in write.table we define the directory path and file name within that function but I want a function in which user can save file with any name in his desired directory.
Just use the file.choose() function,like this:
write.table(yerdata, file = file.choose(new = TRUE))
On Windows, at least, that will bring up a dialog for save-as commands.
Annoyingly the tcltk package doesn't have a function for 'Save As', it only has a file selector for choosing an existing file.
Luckily you can take the DIY approach via some tcl calls:
require(tcltk)
write.table(yerdata,file = tclvalue(tcl("tk_getSaveFile")))
The tk_choose.files function source could be used as a template to write a nicer interface to tcl("tk_getSaveFile") if needed. Does seem to be a glaring omission in package:tcltk though...
Using gWidgets:
gfile("Save yerdata", type = "save", handler = function(h, ...)
{
write.table(yerdata, file = h$file)
})
One (perhaps less than ideal) option would be to use readline to prompt the user for the full path and file name (or just the file name if you want to programmatically choose the directory) and then simply pass that value on the write.table. Here's a sketch:
FILE_PATH <- readline(prompt = "Enter a full path and file name: ")
#Some checking to make sure you got a valid file path...
write.table(yerdata, file = FILE_PATH)
Note that as per ?readline this will really only work when running R interactively.
As it is 2017 now, the tcltk2 package is an improvement of tcltk:
library(tcltk2)
filename <- tclvalue(tkgetSaveFile())
if (!nchar(filename)) {
tkmessageBox(message = "No file was selected!")
} else {
tkmessageBox(message = paste("The file selected was", filename))
}
And the use of filters, let's say one should only save as JPG/JPEG:
jpeg_filename <- tclvalue(
tkgetSaveFile(initialfile = "foo.jpg",
filetypes = "{ {JPEG Files} {.jpg .jpeg} } { {All Files} * }")
)