如何修剪前导和尾随空白?

发布于 2024-08-22 01:20:36 字数 1111 浏览 10 评论 0原文

我在处理 data.frame 中的前导和尾随空格时遇到一些问题。

例如,我根据特定条件查看 data.frame 中的特定

> myDummy[myDummy$country == c("Austria"),c(1,2,3:7,19)] 



[1] codeHelper     country        dummyLI    dummyLMI       dummyUMI       

[6] dummyHInonOECD dummyHIOECD    dummyOECD      

<0 rows> (or 0-length row.names)

我想知道为什么自奥地利国家以来我没有获得预期输出显然存在于我的 data.frame 中。在查看了我的代码历史记录并试图找出问题所在后,我尝试了:

> myDummy[myDummy$country == c("Austria "),c(1,2,3:7,19)]
   codeHelper  country dummyLI dummyLMI dummyUMI dummyHInonOECD dummyHIOECD
18        AUT Austria        0        0        0              0           1
   dummyOECD
18         1

我在命令中所做的所有更改都是在奥地利之后增加了一个空格。

显然还会出现更多恼人的问题。例如,当我喜欢根据国家/地区列合并两个框架时。一个 data.frame 使用 “Austria”,而另一个框架则使用 “Austria”。匹配不起作用。

  1. 有没有一种好方法可以“显示”屏幕上的空白,以便我意识到问题所在?
  2. 我可以删除 R 中的前导和尾随空格吗?

到目前为止,我曾经编写过一个简单的 Perl 脚本,它消除了白人的步伐,但这会很好如果我能以某种方式在 R 中做到这一点。

I am having some trouble with leading and trailing white space in a data.frame.

For example, I look at a specific row in a data.frame based on a certain condition:

> myDummy[myDummy$country == c("Austria"),c(1,2,3:7,19)] 



[1] codeHelper     country        dummyLI    dummyLMI       dummyUMI       

[6] dummyHInonOECD dummyHIOECD    dummyOECD      

<0 rows> (or 0-length row.names)

I was wondering why I didn't get the expected output since the country Austria obviously existed in my data.frame. After looking through my code history and trying to figure out what went wrong I tried:

> myDummy[myDummy$country == c("Austria "),c(1,2,3:7,19)]
   codeHelper  country dummyLI dummyLMI dummyUMI dummyHInonOECD dummyHIOECD
18        AUT Austria        0        0        0              0           1
   dummyOECD
18         1

All I have changed in the command is an additional white space after Austria.

Further annoying problems obviously arise. For example, when I like to merge two frames based on the country column. One data.frame uses "Austria " while the other frame has "Austria". The matching doesn't work.

  1. Is there a nice way to 'show' the white space on my screen so that I am aware of the problem?
  2. And can I remove the leading and trailing white space in R?

So far I used to write a simple Perl script which removes the whites pace, but it would be nice if I can somehow do it inside R.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

情场扛把子 2024-08-29 01:20:36

从 R 3.2.0 开始,引入了一个新函数来删除前导/尾随空格:

trimws()

请参阅:删除前导/尾随空格

As of R 3.2.0 a new function was introduced for removing leading/trailing white spaces:

trimws()

See: Remove Leading/Trailing Whitespace

风和你 2024-08-29 01:20:36

最好的方法可能是在读取数据文件时处理尾随空格。如果您使用read.csvread.table,您可以设置参数strip.white=TRUE

如果您想随后清理字符串,可以使用以下函数之一:

# Returns string without leading white space
trim.leading <- function (x)  sub("^\\s+", "", x)

# Returns string without trailing white space
trim.trailing <- function (x) sub("\\s+$", "", x)

# Returns string without leading or trailing white space
trim <- function (x) gsub("^\\s+|\\s+$", "", x)

myDummy$country 上使用以下函数之一:

 myDummy$country <- trim(myDummy$country)

“显示”您可以使用的空格:

 paste(myDummy$country)

这将显示字符串用引号 (") 括起来,使空格更容易被发现。

Probably the best way is to handle the trailing white spaces when you read your data file. If you use read.csv or read.table you can set the parameterstrip.white=TRUE.

If you want to clean strings afterwards you could use one of these functions:

# Returns string without leading white space
trim.leading <- function (x)  sub("^\\s+", "", x)

# Returns string without trailing white space
trim.trailing <- function (x) sub("\\s+
quot;, "", x)

# Returns string without leading or trailing white space
trim <- function (x) gsub("^\\s+|\\s+
quot;, "", x)

To use one of these functions on myDummy$country:

 myDummy$country <- trim(myDummy$country)

To 'show' the white space you could use:

 paste(myDummy$country)

which will show you the strings surrounded by quotation marks (") making white spaces easier to spot.

吖咩 2024-08-29 01:20:36

要操作空白,请使用 stringr 包中的 str_trim() 。
该软件包的手册日期为 2013 年 2 月 15 日,位于 CRAN 中。
该函数还可以处理字符串向量。

install.packages("stringr", dependencies=TRUE)
require(stringr)
example(str_trim)
d4$clean2<-str_trim(d4$V2)

(感谢评论者:R. Cotton)

To manipulate the white space, use str_trim() in the stringr package.
The package has manual dated Feb 15, 2013 and is in CRAN.
The function can also handle string vectors.

install.packages("stringr", dependencies=TRUE)
require(stringr)
example(str_trim)
d4$clean2<-str_trim(d4$V2)

(Credit goes to commenter: R. Cotton)

橪书 2024-08-29 01:20:36

一个简单的函数,用于删除前导和尾随空格:

trim <- function( x ) {
  gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
}

用法:

> text = "   foo bar  baz 3 "
> trim(text)
[1] "foo bar  baz 3"

A simple function to remove leading and trailing whitespace:

trim <- function( x ) {
  gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
}

Usage:

> text = "   foo bar  baz 3 "
> trim(text)
[1] "foo bar  baz 3"
纵山崖 2024-08-29 01:20:36

广告 1) 要查看空格,您可以使用修改后的参数直接调用 print.data.frame

print(head(iris), quote=TRUE)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width  Species
# 1        "5.1"       "3.5"        "1.4"       "0.2" "setosa"
# 2        "4.9"       "3.0"        "1.4"       "0.2" "setosa"
# 3        "4.7"       "3.2"        "1.3"       "0.2" "setosa"
# 4        "4.6"       "3.1"        "1.5"       "0.2" "setosa"
# 5        "5.0"       "3.6"        "1.4"       "0.2" "setosa"
# 6        "5.4"       "3.9"        "1.7"       "0.4" "setosa"

另请参阅 ?print.data.frame 了解其他选项。

Ad 1) To see white spaces you could directly call print.data.frame with modified arguments:

print(head(iris), quote=TRUE)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width  Species
# 1        "5.1"       "3.5"        "1.4"       "0.2" "setosa"
# 2        "4.9"       "3.0"        "1.4"       "0.2" "setosa"
# 3        "4.7"       "3.2"        "1.3"       "0.2" "setosa"
# 4        "4.6"       "3.1"        "1.5"       "0.2" "setosa"
# 5        "5.0"       "3.6"        "1.4"       "0.2" "setosa"
# 6        "5.4"       "3.9"        "1.7"       "0.4" "setosa"

See also ?print.data.frame for other options.

妳是的陽光 2024-08-29 01:20:36

使用 grep< /em> 或grepl 查找带有空格和 sub 来摆脱它们。

names<-c("Ganga Din\t", "Shyam Lal", "Bulbul ")
grep("[[:space:]]+$", names)
[1] 1 3
grepl("[[:space:]]+$", names)
[1]  TRUE FALSE  TRUE
sub("[[:space:]]+$", "", names)
[1] "Ganga Din" "Shyam Lal" "Bulbul"

Use grep or grepl to find observations with white spaces and sub to get rid of them.

names<-c("Ganga Din\t", "Shyam Lal", "Bulbul ")
grep("[[:space:]]+
quot;, names)
[1] 1 3
grepl("[[:space:]]+
quot;, names)
[1]  TRUE FALSE  TRUE
sub("[[:space:]]+
quot;, "", names)
[1] "Ganga Din" "Shyam Lal" "Bulbul"
°如果伤别离去 2024-08-29 01:20:36

删除前导和尾随空白也可以通过 gdata 包中的 trim() 函数来实现:

require(gdata)
example(trim)

使用示例:

> trim("   Remove leading and trailing blanks    ")
[1] "Remove leading and trailing blanks"

我更愿意将答案作为注释添加到 user56 的,但我还不能作为独立的人编写回答。

Removing leading and trailing blanks might be achieved through the trim() function from the gdata package as well:

require(gdata)
example(trim)

Usage example:

> trim("   Remove leading and trailing blanks    ")
[1] "Remove leading and trailing blanks"

I'd prefer to add the answer as comment to user56's, but I am yet unable so writing as an independent answer.

泛泛之交 2024-08-29 01:20:36

另一种选择是使用 stringi 包中的 stri_trim 函数,该函数默认删除前导空格和尾随空格:

> x <- c("  leading space","trailing space   ")
> stri_trim(x)
[1] "leading space"  "trailing space"

如果仅删除前导空格,请使用 stri_trim_left 。如果仅删除尾随空格,请使用 stri_trim_right。当您想要删除其他前导或尾随字符时,必须使用 pattern = 进行指定。

另请参阅 ?stri_trim 了解更多信息。

Another option is to use the stri_trim function from the stringi package which defaults to removing leading and trailing whitespace:

> x <- c("  leading space","trailing space   ")
> stri_trim(x)
[1] "leading space"  "trailing space"

For only removing leading whitespace, use stri_trim_left. For only removing trailing whitespace, use stri_trim_right. When you want to remove other leading or trailing characters, you have to specify that with pattern =.

See also ?stri_trim for more info.

鲸落 2024-08-29 01:20:36

我创建了一个 trim.strings () 函数来修剪前导和/或尾随空白,如下

# Arguments:    x - character vector
#            side - side(s) on which to remove whitespace 
#                   default : "both"
#                   possible values: c("both", "leading", "trailing")

trim.strings <- function(x, side = "both") { 
    if (is.na(match(side, c("both", "leading", "trailing")))) { 
      side <- "both" 
      } 
    if (side == "leading") { 
      sub("^\\s+", "", x)
      } else {
        if (side == "trailing") {
          sub("\\s+$", "", x)
    } else gsub("^\\s+|\\s+$", "", x)
    } 
} 

所示:

a <- c("   ABC123 456    ", " ABC123DEF          ")

# returns string without leading and trailing whitespace
trim.strings(a)
# [1] "ABC123 456" "ABC123DEF" 

# returns string without leading whitespace
trim.strings(a, side = "leading")
# [1] "ABC123 456    "      "ABC123DEF          "

# returns string without trailing whitespace
trim.strings(a, side = "trailing")
# [1] "   ABC123 456" " ABC123DEF"   

I created a trim.strings () function to trim leading and/or trailing whitespace as:

# Arguments:    x - character vector
#            side - side(s) on which to remove whitespace 
#                   default : "both"
#                   possible values: c("both", "leading", "trailing")

trim.strings <- function(x, side = "both") { 
    if (is.na(match(side, c("both", "leading", "trailing")))) { 
      side <- "both" 
      } 
    if (side == "leading") { 
      sub("^\\s+", "", x)
      } else {
        if (side == "trailing") {
          sub("\\s+$", "", x)
    } else gsub("^\\s+|\\s+$", "", x)
    } 
} 

For illustration,

a <- c("   ABC123 456    ", " ABC123DEF          ")

# returns string without leading and trailing whitespace
trim.strings(a)
# [1] "ABC123 456" "ABC123DEF" 

# returns string without leading whitespace
trim.strings(a, side = "leading")
# [1] "ABC123 456    "      "ABC123DEF          "

# returns string without trailing whitespace
trim.strings(a, side = "trailing")
# [1] "   ABC123 456" " ABC123DEF"   
李白 2024-08-29 01:20:36

如果输入之间有多个空格,则会出现另一个相关问题:

> a <- "  a string         with lots   of starting, inter   mediate and trailing   whitespace     "

然后,您可以使用 split 参数的正则表达式轻松将此字符串拆分为“真实”标记:

> strsplit(a, split=" +")
[[1]]
 [1] ""           "a"          "string"     "with"       "lots"
 [6] "of"         "starting,"  "inter"      "mediate"    "and"
[11] "trailing"   "whitespace"

请注意,如果在(非空)字符串的开头,输出的第一个元素是 '""',但如果字符串末尾有匹配项,则输出与删除匹配项相同。

Another related problem occurs if you have multiple spaces in between inputs:

> a <- "  a string         with lots   of starting, inter   mediate and trailing   whitespace     "

You can then easily split this string into "real" tokens using a regular expression to the split argument:

> strsplit(a, split=" +")
[[1]]
 [1] ""           "a"          "string"     "with"       "lots"
 [6] "of"         "starting,"  "inter"      "mediate"    "and"
[11] "trailing"   "whitespace"

Note that if there is a match at the beginning of a (non-empty) string, the first element of the output is ‘""’, but if there is a match at the end of the string, the output is the same as with the match removed.

智商已欠费 2024-08-29 01:20:36

使用 dplyr/tidyverse mutate_allstr_trim 来修剪整个数据框:

myDummy %>%
  mutate_all(str_trim)
library(tidyverse)
set.seed(335)
df <- mtcars %>%
        rownames_to_column("car") %>%
        mutate(car = ifelse(runif(nrow(mtcars)) > 0.4, car, paste0(car, " "))) %>%
        select(car, mpg)

print(head(df), quote = T)
#>                    car    mpg
#> 1         "Mazda RX4 " "21.0"
#> 2      "Mazda RX4 Wag" "21.0"
#> 3        "Datsun 710 " "22.8"
#> 4    "Hornet 4 Drive " "21.4"
#> 5 "Hornet Sportabout " "18.7"
#> 6           "Valiant " "18.1"

df_trim <- df %>%
  mutate_all(str_trim)

print(head(df_trim), quote = T)  
#>                   car    mpg
#> 1         "Mazda RX4"   "21"
#> 2     "Mazda RX4 Wag"   "21"
#> 3        "Datsun 710" "22.8"
#> 4    "Hornet 4 Drive" "21.4"
#> 5 "Hornet Sportabout" "18.7"
#> 6           "Valiant" "18.1"

reprex 包 (v0.3.0)

Use dplyr/tidyverse mutate_all with str_trim to trim the entire data frame:

myDummy %>%
  mutate_all(str_trim)
library(tidyverse)
set.seed(335)
df <- mtcars %>%
        rownames_to_column("car") %>%
        mutate(car = ifelse(runif(nrow(mtcars)) > 0.4, car, paste0(car, " "))) %>%
        select(car, mpg)

print(head(df), quote = T)
#>                    car    mpg
#> 1         "Mazda RX4 " "21.0"
#> 2      "Mazda RX4 Wag" "21.0"
#> 3        "Datsun 710 " "22.8"
#> 4    "Hornet 4 Drive " "21.4"
#> 5 "Hornet Sportabout " "18.7"
#> 6           "Valiant " "18.1"

df_trim <- df %>%
  mutate_all(str_trim)

print(head(df_trim), quote = T)  
#>                   car    mpg
#> 1         "Mazda RX4"   "21"
#> 2     "Mazda RX4 Wag"   "21"
#> 3        "Datsun 710" "22.8"
#> 4    "Hornet 4 Drive" "21.4"
#> 5 "Hornet Sportabout" "18.7"
#> 6           "Valiant" "18.1"

Created on 2021-05-07 by the reprex package (v0.3.0)

浪荡不羁 2024-08-29 01:20:36

最好的方法是 trimws()

以下代码将将此函数应用于整个数据帧。

mydataframe<- data.frame(lapply(mydataframe, trimws),stringsAsFactors = FALSE)

The best method is trimws().

The following code will apply this function to the entire dataframe.

mydataframe<- data.frame(lapply(mydataframe, trimws),stringsAsFactors = FALSE)
无力看清 2024-08-29 01:20:36
myDummy[myDummy$country == "Austria "] <- "Austria"

此后,您需要强制 R 不将“Austria”识别为关卡。假设您还有 "USA""Spain" 作为级别:

myDummy$country = factor(myDummy$country, levels=c("Austria", "USA", "Spain"))

它比得票最高的响应稍微不那么令人生畏,但它应该仍然有效。

myDummy[myDummy$country == "Austria "] <- "Austria"

After this, you'll need to force R not to recognize "Austria " as a level. Let's pretend you also have "USA" and "Spain" as levels:

myDummy$country = factor(myDummy$country, levels=c("Austria", "USA", "Spain"))

It is a little less intimidating than the highest voted response, but it should still work.

故事还在继续 2024-08-29 01:20:36

本线程中主要方法的基准测试。这并没有捕获所有奇怪的情况,但到目前为止我们仍然缺少 str_trim 删除空格而 trimws 不删除的示例(请参阅理查德·特尔福德对此答案的评论)。似乎并不重要 - gsub 选项似乎是最快的:)

x <- c(" lead", "trail ", " both ", " both and middle ", " _special")
## gsub function from https://stackoverflow.com/a/2261149/7941188 
## this is NOT the function from user Bernhard Kausler, which uses 
## a much less concise regex 
gsub_trim <- function (x) gsub("^\\s+|\\s+$", "", x)

res <- microbenchmark::microbenchmark(
  gsub = gsub_trim(x),
  ## https://stackoverflow.com/a/30210713/7941188
  trimws = trimws(x),
  ## https://stackoverflow.com/a/15007398/7941188
  str_trim = stringr::str_trim(x),
  times = 10^5
)
res
#> Unit: microseconds
#>      expr    min     lq      mean median       uq       max neval cld
#>      gsub 20.201 22.788  31.43943 24.654  28.4115  5303.741 1e+05 a  
#>    trimws 38.204 41.980  61.92218 44.420  51.1810 40363.860 1e+05  b 
#>  str_trim 88.672 92.347 116.59186 94.542 105.2800 13618.673 1e+05   c
ggplot2::autoplot(res)

sessionInfo()
#> R version 4.0.3 (2020-10-10)
#> Platform: x86_64-apple-darwin17.0 (64-bit)
#> Running under: macOS Big Sur 10.16
#> 
#> locale:
#> [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> loaded via a namespace (and not attached):
#>  stringr_1.4.0  

Benchmarking of the main approaches in this thread. This is not capturing all weird cases, but so far we are still lacking the example where str_trim removes whitespace and trimws doesn't (see Richard Telford's comment to this answer). Doesn't seem to matter - the gsub option seems to be fastest :)

x <- c(" lead", "trail ", " both ", " both and middle ", " _special")
## gsub function from https://stackoverflow.com/a/2261149/7941188 
## this is NOT the function from user Bernhard Kausler, which uses 
## a much less concise regex 
gsub_trim <- function (x) gsub("^\\s+|\\s+
quot;, "", x)

res <- microbenchmark::microbenchmark(
  gsub = gsub_trim(x),
  ## https://stackoverflow.com/a/30210713/7941188
  trimws = trimws(x),
  ## https://stackoverflow.com/a/15007398/7941188
  str_trim = stringr::str_trim(x),
  times = 10^5
)
res
#> Unit: microseconds
#>      expr    min     lq      mean median       uq       max neval cld
#>      gsub 20.201 22.788  31.43943 24.654  28.4115  5303.741 1e+05 a  
#>    trimws 38.204 41.980  61.92218 44.420  51.1810 40363.860 1e+05  b 
#>  str_trim 88.672 92.347 116.59186 94.542 105.2800 13618.673 1e+05   c
ggplot2::autoplot(res)

sessionInfo()
#> R version 4.0.3 (2020-10-10)
#> Platform: x86_64-apple-darwin17.0 (64-bit)
#> Running under: macOS Big Sur 10.16
#> 
#> locale:
#> [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> loaded via a namespace (and not attached):
#>  stringr_1.4.0  

戴着白色围巾的女孩 2024-08-29 01:20:36

我试过修剪()。它适用于空格和“\n”。

x = '\n              Harden, J.\n              '

trim(x)

I tried trim(). It works well with white spaces as well as the '\n'.

x = '\n              Harden, J.\n              '

trim(x)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文