I need to duplicate one column or variable with conditionals

42 Views Asked by At

I'm working on some data and almost 4 variables has this characteristics:

DptResidence          DeathIndex
-1-Not defined        0-No
54-North              1-Yes
81-South              0-No

I need to create or duplicate this variables erasing "-" from numbers, but maintaining relationship between numbers with names, i.e.

CodeResidence        DptResidence      DeathIndexCod     DeathIndex
1                    Not defined       0                 No
54                   North             1                 Yes
81                   South             0                 No

I've tried to find some information online, however I can't find something useful to solve this problem.

1

There are 1 best solutions below

2
Onyambu On

Using base R you could do:

d <- data.frame(gsub("(\\d)-","\\1,",as.matrix(df)))
nms <- c("CodeResidence", "DptResidence", "DeathIndexCod", "DeathIndex")
read.csv(text = do.call(paste, c(sep=',', d)), col.names = nms, header = FALSE)

  CodeResidence DptResidence DeathIndexCod DeathIndex
1            -1  Not defined             0         No
2            54        North             1        Yes
3            81        South             0         No