1

I'm trying to remove the white space in the filename that I have created using the follwing code:

epoch <- strsplit(toString(files[val]),split='.', fixed=TRUE)[[1]][1]
    print(paste(epoch,".csv"))

The current output gives me: "2016_Q3 .csv". I would like to remove the whitespace between the 3 and the .so the final string looks like "2016_Q3.csv"

I have looked at gsub and trimws, but can't get them to work.

lmo
  • 37,904
  • 9
  • 56
  • 69
Stacey
  • 4,825
  • 17
  • 58
  • 99

4 Answers4

5

paste puts a space by default. Instead do:

paste(epoch,".csv",sep="")

or

paste0(epoch,".csv")

Both return:

[1] "2016_Q3.csv"
Lamia
  • 3,845
  • 1
  • 12
  • 19
3

If you want to use gsub it becomes a pretty simple task.

str <- "2016_Q3 .csv"
gsub(" ","",str)

Gives you:

"2016_Q3.csv"
Michael Kirchner
  • 869
  • 1
  • 7
  • 17
2

We can use sub to match one or more spaces (\\s+) followed by a dot (\\. - escape the dot as it is a metacharacter implying any character) and replace it with .

sub("\\s+\\.", ".", str1)
#[1] "2016_Q3.csv"

Using the OP's example, even a non-specific (\\s+) should work

sub("\\s+", "", str1)

data

str1 <- "2016_Q3 .csv"
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Using stringr:

library(stringr)
epoch = str_replace(epoch, " ", "")
rsmith54
  • 818
  • 9
  • 15