选择性地将“-”替换为“.”使用 gsub()

Selectively replace "-" by "." using gsub()

> df <- data.frame(x=c('a-b','c-d','e-f'),y=c('[1-2]','(3-4)','[5-6)'),stringsAsFactors=F)
> df
    x     y
1 a-b [1-2]
2 c-d (3-4)
3 e-f [5-6)

我正在尝试使用gsub()扫描df的所有列,但仅从带有字母的列中将"-"替换为".",使它看起来像这样:

> df
    x     y
1 a.b [1-2]
2 c.d (3-4)
3 e.f [5-6)

使用sapply(names(df), function(x) gsub("\-", ".", df[, x]))无效:

> sapply(names(df), function(x) gsub("\-", ".", df[, x]))
     x     y      
[1,] "a.b" "[1.2]"
[2,] "c.d" "(3.4)"
[3,] "e.f" "[5.6)"

是否有更好的方法来执行此操作,使用gsub()或类似make.names()的方法可以 select 列?

谢谢

我们可以把pattern换成字母之间的-

df[] <- lapply(df, gsub, pattern = '([[:alpha:]]+)-([[:alpha:]]+)',  replacement ="\1.\2")
df
#    x     y
#1 a.b [1-2]
#2 c.d (3-4)
#3 e.f [5-6)