【问题标题】:How can I reset factors of a vector after modify strings? [duplicate]修改字符串后如何重置向量的因子? [复制]
【发布时间】:2016-07-06 15:03:00
【问题描述】:

修改字符串后如何重置向量的因子/级别?

library(stringr)
x <- c("  x1", "x1", "x2 ", " x2", "x1 ", "x2") # Whitespace left or right
as.character(x)
[1] "  x1" "x1"   "x2 "  " x2"  "x1 "  "x2" 
str_replace_all(x, fixed(" "), "")
[1] "x1" "x1" "x2" "x2" "x1" "x2"
factor(x)
[1]   x1 x1   x2    x2  x1   x2
Levels: x1  x2 x1 x1  x2 x2`

我想要这样的结果:

[1] x1 x1 x2 x2 x1 x2
Levels:   x1  x2

【问题讨论】:

    标签: r string vector trim


    【解决方案1】:

    不需要任何软件包。你可以这样做

    factor(trimws(x))
    # [1] x1 x1 x2 x2 x1 x2
    # Levels: x1 x2
    

    trimws() 用于修剪空白,可用于基础 R (>= 3.2.0)。

    【讨论】:

      【解决方案2】:
      library("stringr")
      x <- c("  x1", "x1", "x2 ", " x2", "x1 ", "x2") #Whitespace left or right
      
      # Assign the following to a new variable
      x2 <- str_replace_all(x, fixed(" "), "")
      
      # Factor of the new variable
      factor(x2)
      

      【讨论】:

      • 还有特殊用途的stringr::str_trim(),它将处理任何类型的空白,而不仅仅是空格。
      【解决方案3】:

      如果R版本是gsub。

      factor(gsub("^\\s+|\\s+$", "", x))
      #[1] x1 x1 x2 x2 x1 x2
      #Levels: x1 x2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-04
        相关资源
        最近更新 更多