0

I have a variable with numeric integers -6 to 3450. I want to replace anything <0 with its absolute value and 00 in front.

So for example

-6, -5, -4, -3, -2, -1, 0 

Become

006, 005, 004, 003, 002, 001, 000

And all the other integers stay the same.

I think there must be a way to do this with ‘replace’.. my best guess..

data <- replace(data$var1, data$var1 < 1, ‘00 + abs()’) 
steveb
  • 5,382
  • 2
  • 27
  • 36
scotiaboy
  • 43
  • 6
  • Is it ok, if your column is chr datatype? – Karthik S Dec 23 '20 at 05:43
  • Very likely a duplicate of [How to add leading zeros?](https://stackoverflow.com/questions/5812493/how-to-add-leading-zeros) unless there is some further complication. E.g.: `replace(x, x <= 0, sprintf("%03d", abs(x))[x <= 0] )` – thelatemail Dec 23 '20 at 05:48
  • @thelatemail agreed, this looks like a duplicate of what you linked to. – steveb Dec 23 '20 at 06:06

3 Answers3

0

In TidyR:

library(tidyverse)
library(stringr)
df <- tibble(x=c(-6, -5 , 100, 101), y=rnorm(4))
df %>% mutate(x = ifelse(x < 0, str_pad(abs(x), pad = "0", width = 3), x))

enter image description here

MR_MPI-BGC
  • 265
  • 3
  • 11
0

Do you want this?

v <- -6:3450

ifelse(v <= 0, formatC(abs(v), width = 3, flag = "0"), v)

   [1] "006" "005" "004" "003" "002" "001" "000"   "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"  
  [16] "9"   "10"  "11"  "12"  "13"  "14"  "15"  "16"  "17"  "18"  "19"  "20"  "21"  "22"  "23"
.......
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
0

Data

s <- data.frame(var1=-6:3400)

Looks like

> head(s)
  var1
1   -6
2   -5
3   -4
4   -3
5   -2
6   -1

Create requested var2

library(dplyr)
ss <- mutate(s, var2 = ifelse(var1<0, as.character(sprintf("%03d", var1*-1)), var1)) 

> head(ss)
  var1 var2
1   -6  006
2   -5  005
3   -4  004
4   -3  003
5   -2  002
6   -1  001
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
cmirian
  • 2,572
  • 3
  • 19
  • 59