Search code examples
rcsvsubstringpastequoting

Syntax error when adding quote character before minus sign to fixup for csv export to Excel


In my dataset I have a column where some characters start with a minus sign. This causes issues when exporting as a csv and opening in Excel. As such I would like to add a ' for the rows where the first character is a -.

df <- data.frame(a=c("a","b","c","d","e"),
                 b=c("test","-test","test2","-","-test3"))

I've tried this but get the following error:

df$b[substring(df$b,1,1)=="-"] <- paste0("'",df$bsubstring(df$b,1,1)=="-")

Error in paste0("'", df$bsubstring(df$b, 1, 1) == "-") :
attempt to apply non-function


Solution

  • Here is an option with sub

    df$b <- sub("-", "'-", df$b)
    df$b
    #[1] "test"    "'-test"  "test2"   "'-"      "'-test3"