How to extract - sign from tail and place it before the number

Viewed 50

I got a .txt file which has sign at the end of the number.

When I tried converting it into numeric, the -ve values are turning into NA as the data is in character format. I even tried, flagging those -ve values and multiplying flagged value by '-1'.

Since I have around 25 such columns. It is getting complicated. Can anyone suggest me simple way to do this.

Below is the sample data I prepared,

R1 <- c("15515.88-","5156.04","65656","1566.1-")
R2 <- c("515","5156.11-","415-","1455-")
R3 <- c("123.14-","9875-","1247-","778.04-")
df <- data.frame(R1,R2,R3)

My expected output is -ve symbol at the initial,

    R1         R2        R3
-15515.88     515      -123.14
 5156.04     -5156.11  -9875
 65656       -415      -1247
-1566.1      -1455     -778.04

Your kind help is needed

3 Answers

In base R you can use lapply to process one column at a time with regex and convert to numeric.

df[] <- lapply(df, function(x) as.numeric(sub("(.+)(-)", "\\2\\1", x)))
df

#          R1       R2       R3
# 1 -15515.88   515.00  -123.14
# 2   5156.04 -5156.11 -9875.00
# 3  65656.00  -415.00 -1247.00
# 4  -1566.10 -1455.00  -778.04

One solution in base R would be

df[] <- lapply(df, function(x) {as.numeric(ifelse(grepl("-", x), paste0("-", gsub("-", "", x)), x))})

Basically it works like this: if a - is present, you remove it and add another - at the start of the value, and then you convert the column to numeric.

Output

#          R1       R2       R3
# 1 -15515.88   515.00  -123.14
# 2   5156.04 -5156.11 -9875.00
# 3  65656.00  -415.00 -1247.00
# 4  -1566.10 -1455.00  -778.04
rep.format <- function(num){
  ind <- grepl("-", num)
  num[ind] <-  paste0("-", sub("-", "", num[ind]), "")
  num
}

R1 <- c("15515.88-","5156.04","65656","1566.1-")
R2 <- c("515","5156.11-","415-","1455-")
R3 <- c("123.14-","9875-","1247-","778.04-")

df <- data.frame(rep.format(R1),rep.format(R2),rep.format(R3))
df

I hope that this helps!

Related