我有一些麻烦的前导和尾随空白在一个数据。框架。

例如,我根据特定条件查看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)

我想知道为什么我没有得到预期的输出,因为奥地利显然存在于我的数据框架中。在查看了我的代码历史并试图找出错误后,我尝试了:

> 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”,而另一个frame使用“Austria”。匹配不起作用。

有没有一种很好的方法来“显示”屏幕上的空白,让我意识到这个问题? 我能移除R开头和结尾的空白吗?

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


当前回答

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。

其他回答

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

trimws()

参见:移除前导/尾随空格

也可以通过gdata包中的trim()函数来移除前导和后面的空格:

require(gdata)
example(trim)

使用的例子:

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

我更喜欢把答案作为评论添加到user56的,但我还不能作为一个独立的答案写作。

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

在这之后,你需要强制R不承认“奥地利”是一个关卡。让我们假设你也有“USA”和“Spain”作为关卡:

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

这比得票最高的回答要少一些威慑力,但它仍然有效。

使用dplyr/tidyverse mutate_all和str_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包于2021-05-07创建(v0.3.0)

我创建了一个修剪。string()函数修剪前导和/或尾随空格,如下所示:

# 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"