184

所以" xx yy 11 22 33 "会变成"xxyy112233"。我怎样才能做到这一点?

4

9 回答 9

294

一般来说,我们想要一个矢量化的解决方案,所以这里有一个更好的测试示例:

whitespace <- " \t\n\r\v\f" # space, tab, newline, 
                            # carriage return, vertical tab, form feed
x <- c(
  " x y ",           # spaces before, after and in between
  " \u2190 \u2192 ", # contains unicode chars
  paste0(            # varied whitespace     
    whitespace, 
    "x", 
    whitespace, 
    "y", 
    whitespace, 
    collapse = ""
  ),   
  NA                 # missing
)
## [1] " x y "                           
## [2] " ← → "                           
## [3] " \t\n\r\v\fx \t\n\r\v\fy \t\n\r\v\f"
## [4] NA

基础 R 方法:gsub

gsubfixed = TRUE用另一个字符串替换字符串 ( ) 或正则表达式 ( fixed = FALSE,默认值) 的所有实例。要删除所有空格,请使用:

gsub(" ", "", x, fixed = TRUE)
## [1] "xy"                            "←→"             
## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA 

正如 DWin 所指出的,在这种情况下fixed = TRUE不是必需的,但会提供稍微更好的性能,因为匹配固定字符串比匹配正则表达式更快。

如果要删除所有类型的空格,请使用:

gsub("[[:space:]]", "", x) # note the double square brackets
## [1] "xy" "←→" "xy" NA 

gsub("\\s", "", x)         # same; note the double backslash

library(regex)
gsub(space(), "", x)       # same

"[:space:]"是匹配所有空格字符的特定于 R 的正则表达式组。 \s是一个独立于语言的正则表达式,它做同样的事情。


stringr方法:str_replace_allstr_trim

stringr围绕基本 R 函数提供了更多人类可读的包装器(尽管截至 2014 年 12 月,开发版本有一个基于 的分支stringi,如下所述)。使用 [ 的上述命令的等价物str_replace_all][3]是:

library(stringr)
str_replace_all(x, fixed(" "), "")
str_replace_all(x, space(), "")

stringr还具有str_trim仅删除前导和尾随空格的功能。

str_trim(x) 
## [1] "x y"          "← →"          "x \t\n\r\v\fy" NA    
str_trim(x, "left")    
## [1] "x y "                   "← → "    
## [3] "x \t\n\r\v\fy \t\n\r\v\f" NA     
str_trim(x, "right")    
## [1] " x y"                   " ← →"    
## [3] " \t\n\r\v\fx \t\n\r\v\fy" NA      

stringi方法:stri_replace_all_charclassstri_trim

stringi建立在独立于平台的ICU 库之上,并具有广泛的字符串操作函数集。上面的等价物是:

library(stringi)
stri_replace_all_fixed(x, " ", "")
stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "")

这是被认为是空白的 Unicode 代码点集的另一种语法,"\\p{WHITE_SPACE}"相当于和。对于更复杂的正则表达式替换,还有."[[:space:]]""\\s"space()stri_replace_all_regex

stringi还具有修剪功能

stri_trim(x)
stri_trim_both(x)    # same
stri_trim(x, "left")
stri_trim_left(x)    # same
stri_trim(x, "right")  
stri_trim_right(x)   # same
于 2011-05-13T12:55:59.557 回答
25

我刚刚了解了使用 str_trim( , side="both") 从字符串的开头和结尾删除空格的“stringr”包,但它也有一个替换功能,因此:

a <- " xx yy 11 22 33 " 
str_replace_all(string=a, pattern=" ", repl="")

[1] "xxyy112233"
于 2013-06-26T13:02:40.410 回答
16
x = "xx yy 11 22 33"

gsub(" ", "", x)

> [1] "xxyy112233"
于 2017-09-26T08:49:35.277 回答
15

用于[[:blank:]]匹配任何类型的水平空白字符。

gsub("[[:blank:]]", "", " xx yy 11 22  33 ")
# [1] "xxyy112233"
于 2015-10-01T10:16:39.790 回答
9

请注意,上面写的灵魂只删除了空格。如果您还想stri_replace_all_charclassstringi包中删除选项卡或新行使用。

library(stringi)
stri_replace_all_charclass("   ala \t  ma \n kota  ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"
于 2013-07-16T11:20:39.157 回答
6

tidyversestr_squish()包中的功能很神奇!stringr

library(dplyr)
library(stringr)

df <- data.frame(a = c("  aZe  aze s", "wxc  s     aze   "), 
                 b = c("  12    12 ", "34e e4  "), 
                 stringsAsFactors = FALSE)
df <- df %>%
  rowwise() %>%
  mutate_all(funs(str_squish(.))) %>%
  ungroup()
df

# A tibble: 2 x 2
  a         b     
  <chr>     <chr> 
1 aZe aze s 12 12 
2 wxc s aze 34e e4
于 2018-08-07T13:43:23.547 回答
3

可以考虑另一种方法

library(stringr)
str_replace_all(" xx yy 11 22  33 ", regex("\\s*"), "")

#[1] "xxyy112233"

\\s : 匹配空格、制表符、垂直制表符、换行符、换页符、回车符

*:匹配至少 0 次

于 2020-08-09T20:35:16.727 回答
1
income<-c("$98,000.00 ", "$90,000.00 ", "$18,000.00 ", "")

.00使用该trimws()功能后删除空间。

income<-trimws(income)
于 2021-07-22T12:40:03.403 回答
0

从 stringr 库你可以试试这个:

  1. 删除连续的填充空白
  2. 删除填空

    库(字符串)

                2.         1.
                |          |
                V          V
    
        str_replace_all(str_trim(" xx yy 11 22  33 "), " ", "")
    
于 2018-08-29T18:29:46.433 回答