如何删除R中特定位置的字符串中的空格?

Kou*_*ndy 2 regex r gsub

我有很长的名单,我必须计算每个名字出现的次数.但是这些名字与空格混合在一起.

这是一个简单的例子

x <- c(" John D","John D ","John D")
table(x)
x
 John D  John D John D  
      1       1       1 
Run Code Online (Sandbox Code Playgroud)

你可以看到,因为它被识别为三个不同的名称.我要做的就是不要失去John和D之间的空间,我必须删除剩余的空间.请帮忙.谢谢.

akr*_*run 6

尝试:

 library(stringr)
 x1 <- str_trim(x)
 table(x1)
 #x1
 # John D 
 #     3 
Run Code Online (Sandbox Code Playgroud)

要么

  gsub("^ +| +$", "",x)
 #[1] "John D" "John D" "John D"
Run Code Online (Sandbox Code Playgroud)
  • ^ +| +$ - 开头或结尾有0个或更多空格
  • 用""替换它

如果你有这样的矢量:

x <- c("John     D", "   \n John D", "John  D \r")
library(qdap)
strip(x,lower.case=F)
#[1] "John D" "John D" "John D"
Run Code Online (Sandbox Code Playgroud)

如果名称之间没有其他空格str_trim仍然有效

 x <- c("  \nJohn D","John D\r ","John D")
 str_trim(x)
 #[1] "John D" "John D" "John D"
Run Code Online (Sandbox Code Playgroud)


hwn*_*wnd 6

您可以使用gsub删除前导/尾随空白字符.

x <- c("   John D", "John D   ", " John D ")
y <- gsub('^\\s+|\\s+$', '', x)
table(y)
# y
# John D 
#      3 
Run Code Online (Sandbox Code Playgroud)

说明:\s匹配空格(\n,\r,\t,\f,和" ")只在开始^和结束$串的分别.的+量词意味着匹配(1次或更多次).

您也可以使用stringr库包.

library(stringr)
x <- c("   John D", "John D   ", " John D ")
y <- str_trim(x, side='both')
table(y)
# y
# John D 
#      3 
Run Code Online (Sandbox Code Playgroud)