Here is a 1 column data frame:
x <- c(" [CAD] TRAFF-S", "[CAD] SUSP-A ", " [CAD] CRASH", "[CAD] TRAFF-S ", "[CAD] PARKING")
x <- data.frame(x)
> x
x
1 [CAD] TRAFF-S
2 [CAD] SUSP-A
3 [CAD] CRASH
4 [CAD] TRAFF-S
5 [CAD] PARKING
I want to strip the whitespace and was looking at Trim from the qdap package.
The problem is that the input for Trim() and other functions from qdap I want to use expect a vector not a data frame. Normally that would be fine expect due to the pre-processing the vector length might change and thus re-attaching my pre-processed vector to the original df will be hard since the lengths will differ.
In the example data there's some whitespace.
Tried:
> dat.p <- x %>% Trim
> dat.p
[1] "c(2, 4, 1, 5, 3)" # I don't understand what this is doing
What is an appropriate way to iterate over each row in x within a dplyr chain? Or put another way is there a "dplyr esque" way to do this? I would like the variable x to end up being of the same format, a 1 column df witht he same number of rows and columns at the end of the transformation.
You have to mutate
the column x
, and you can use the timws
function, from base
R:
library(dplyr)
dat.p <- x %>%
mutate(x = trimws(x, 'both'))
dat.p
# x
# 1 [CAD] TRAFF-S
# 2 [CAD] SUSP-A
# 3 [CAD] CRASH
# 4 [CAD] TRAFF-S
# 5 [CAD] PARKING
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.