2

How can I reset factors/levels of a vector after modify strings?

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`

I would like a result like:

[1] x1 x1 x2 x2 x1 x2
Levels:   x1  x2
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Rene
  • 21
  • 1

3 Answers3

2

No packages are needed for this. You can do

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

trimws() is for trimming whitespace, and is available in base R (>= 3.2.0).

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
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)
Joachim Schork
  • 2,025
  • 3
  • 25
  • 48
0

We can also use gsub in case the R version is < 3.2.0.

factor(gsub("^\\s+|\\s+$", "", x))
#[1] x1 x1 x2 x2 x1 x2
#Levels: x1 x2
akrun
  • 874,273
  • 37
  • 540
  • 662