在减号前添加引号字符以修复 csv 导出到 Excel 时出现语法错误

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

在我的数据集中有一列,其中一些字符以减号开头。这会导致导出为 csv 并在 Excel 中打开时出现问题。因此,我想为第一个字符是 - 的行添加一个 '

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

我试过了,但出现以下错误:

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

df$b <- as.character(df$b)
ind <- startsWith(df$b,"-")
df$b[ind] <- paste0("'",df$b[ind])
df
# a       b
# 1 a    test
# 2 b  '-test
# 3 c   test2
# 4 d      '-
# 5 e '-test3

此代码df$bsubstring中缺少[]

试试这个

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

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

df
#  a       b
#1 a    test
#2 b  '-test
#3 c   test2
#4 d      '-
#5 e '-test3

这里有一个选项sub

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