Reputation: 1161
I have a large vector of words read from an excel file. Some of those records end with space or "." period. Only in those cases, I need to trim those chars.
Example:
"depresion" "tristeza."
"nostalgia" "preocupacion."
"enojo." "soledad "
"frustracion" "desesperacion "
"angustia." "desconocidos."
Notice some words end normal without "." or " ".
Is there a way to do that?
I have this
substr(conceptos, 1, nchar(conceptos)-1))
to test for the last character (conceptos is this long vector)
Thanks for any advise,
Upvotes: 4
Views: 63
Reputation: 1
Try this:
iif((mid(trim(conceptos), Len(conceptos), 1) == ".") ? substr(conceptos, 1, nchar(conceptos)-1)) : trim(conceptos))
Upvotes: -3
Reputation: 60160
Regular expressions are good for this:
library(stringr)
x = c("depresion", "tristeza.", "nostalgia", "preocupacion.",
"enojo.", "soledad ", "frustracion", "desesperacion ",
"angustia.", "desconocidos.")
x_replaced = str_replace(x, "(\\.|\\s)$", "")
The pattern (\\.|\\s)$
will match a .
or any whitespace that occurs right at the end of the string.
Upvotes: 4
Reputation: 887611
We can use sub
to match zero or more .
or spaces and replace it with blank (""
)
sub("(\\.| )*$", "", v1)
#[1] "depresion" "tristeza" "nostalgia" "preocupacion" "enojo"
#[6] "soledad" "frustracion" "desesperacion"
#[9] "angustia" "desconocidos"
v1 <- c("depresion","tristeza.","nostalgia","preocupacion.",
"enojo.","soledad ","frustracion","desesperacion ",
"angustia.","desconocidos.")
Upvotes: 4