Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何删除R中特定位置的字符串中的空格?_Regex_R_Gsub - Fatal编程技术网

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

Regex 如何删除R中特定位置的字符串中的空格?,regex,r,gsub,Regex,R,Gsub,我有一长串的名字,我必须数一数每个名字出现的次数。但是,名称中混合了空格 下面是一个简单的例子 x <- c(" John D","John D ","John D") table(x) x John D John D John D 1 1 1 x试试: library(stringr) x1 <- str_trim(x) table(x1) #x1 # John D # 3 ^+|+$-0或更多空格在开头或

我有一长串的名字,我必须数一数每个名字出现的次数。但是,名称中混合了空格

下面是一个简单的例子

x <- c(" John D","John D ","John D")
table(x)
x
 John D  John D John D  
      1       1       1 
x试试:

 library(stringr)
 x1 <- str_trim(x)
 table(x1)
 #x1
 # John D 
 #     3 
  • ^+|+$
    -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"
可以使用删除前导/尾随空格字符

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

你能解释一下它是怎么工作的吗?因此,我将学习而不是仅仅复制您的代码我认为
sub
也会以同样的方式执行,因为我们只匹配两端的第一组空格。谢谢@akrun我接受了另一个答案,因为我也从中学到了一些东西。
 x <- c("  \nJohn D","John D\r ","John D")
 str_trim(x)
 #[1] "John D" "John D" "John D"
x <- c("   John D", "John D   ", " John D ")
y <- gsub('^\\s+|\\s+$', '', x)
table(y)
# y
# John D 
#      3 
library(stringr)
x <- c("   John D", "John D   ", " John D ")
y <- str_trim(x, side='both')
table(y)
# y
# John D 
#      3