Reputation: 23
I have a set of downscaled meteorological files that I dowloaded. I need to change the file name to a form that can be recognized by the VIC hydrological model. Example: "macav2livneh_10apr2019_39.6730_-105.61360". I load the downscaled filenames into a dataframe and then use str_replace_all(df.filenames, " ", "") to remove any spaces in the filenames. When I view the new dataframe there are still spaces.
I have searched StackOverflow and the RStudioUsers sites. I copy and paste the strings (file names) from the results of a View command into my editor and the spaces are still present.
library(dplyr)
library(stringr)
df.filenames <- data.frame(list.files("/Users/CoyoteGulch/Documents/ClearCreek/GCM/forcings", all.files = FALSE, full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE))
str_replace_all(df.filenames, " ", "")
View(df.filenames)
I am expecting the results (file names) after the str_replace_all(df.filenames, " ", "") to be a continuous string with no spaces (e.g. "lat39.67241884400long-105.89332598900.csv") but there are spaces (e.g. "lat 39.67241884400 long -105.89332598900.csv") in each row in the dataframe that are the same as the file names in the directory. The filenames in the directory have spaces in the file name. so I believe that the str_replace_all function call above is not having any effect.
Upvotes: 1
Views: 1013
Reputation: 3183
You can do that in base R as:
x <- "some file name.csv"
gsub("[[:space:]]", "", x)
[1] "somefilename.csv"
And in stringr
as:
library(stringr)
str_replace_all(x, fixed(" "), "")
[1] "somefilename.csv"
Upvotes: 1