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

时间:2016-03-19 23:18:13

标签: r string vector trim

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

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

3 个答案:

答案 0 :(得分:2)

这不需要包裹。你可以做到

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

trimws()用于修剪空白,并且在基数R(&gt; = 3.2.0)中可用。

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

我们也可以使用gsub以防R版本< 3.2.0。

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