简体   繁体   中英

R: Replacing and rearranging the order of characters

I would like to re-arrange the order of the symbols and remove certain characters within a dataframe. For example,

14(-)
6(-)
NA
32(+)

to become

-14
-6
NA
32

I tried gsub("()+", "", x) but that just deals with the positive numbers.

I was thinking to split the cells, then apply ifelse on the number column but when I tried to split the cells using str_split(x, "(") from stringr , but I suspect as I had missing values, I got an error message

Error in gregexpr("(", c("14(-)", "6(-)", NA, "32(+)") : invalid regular expression '(', reason 'Missing ')''.

I tried unsuccessfully to replace the missing values with "(" then trying to split them again.

But I'm sure there should be an easier (and much less painful) way to do this.

A possible solution would be to capture the numbers and the symbols into separate groups, reorder and convert to numbers

x <- c("14(-)", "6(-)", NA, "32(+)", "10.3(-)", "13.2(+)")
as.numeric(gsub("(.*)\\((.*)\\)", "\\2\\1", x))
# [1] -14.0  -6.0    NA  32.0 -10.3  13.2

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM