如何在R中gsub一个空的""字符串?

Joh*_*ler 6 r gsub

如何更换空字符串?

这个:

x = c("","b")
gsub("","taco",x)
Run Code Online (Sandbox Code Playgroud)

生产:

"taco"      "tacobtaco"
Run Code Online (Sandbox Code Playgroud)

代替:

"taco"      "b"
Run Code Online (Sandbox Code Playgroud)

有没有办法替换空字符串?

ags*_*udy 12

我会nchar在这里使用:

 x[nchar(x)==0] <- "taco"
Run Code Online (Sandbox Code Playgroud)

编辑

如果您正在寻找性能,那么您应该使用nzchar:

x[!nzchar(x)] <- "taco"
Run Code Online (Sandbox Code Playgroud)


Joh*_*ler 6

x = c("","b")
gsub("^$","taco",x)
Run Code Online (Sandbox Code Playgroud)


Kon*_*lph 5

我不会在语义上使用 \xe2\x80\x99tgsub这里 \xe2\x80\x93 ,我认为gsub替换字符串中的部分。为了替换整个字符串,我只会使用子集。由于您\xe2\x80\x99正在搜索固定字符串(''),因此\xe2\x80\x99甚至不需要正则表达式:

\n\n
x[x == ''] = 'taco'\n
Run Code Online (Sandbox Code Playgroud)\n\n

(当然,这会重新分配原始向量x,而gsub仅返回修改后的结果。)

\n