This is my dataset below. I am trying offset all the values in Col1, Col2, Col3, Col4
by 1
ID Col1 Col2 Col3 Col4
314 3 4 4 3
820 1 3 1 2
223 1 1 3 1
915 1 3 4 4
542 1 2 3 4
521 4 1 3 4
978 4 2 4 2
260 3 3 1 2
892 1 4 1 2
The final dataset should looks like this below
ID Col1 Col2 Col3 Col4
314 2 3 3 2
820 0 2 0 1
223 0 0 2 0
915 0 2 3 3
542 0 1 2 3
521 3 0 2 3
978 3 1 3 1
260 2 2 0 1
892 0 3 0 1
I know a few ways to do this but I am worried they may not give me accurate results. Any suggestions on this is much appreciated. Thanks in advance.
CodePudding user response:
Arithmetic operations are vectorized. We can directly subtract from 1 from the numeric columns and assign it back
df1[-1] <- df1[-1] - 1
-output
> df1
ID Col1 Col2 Col3 Col4
1 314 2 3 3 2
2 820 0 2 0 1
3 223 0 0 2 0
4 915 0 2 3 3
5 542 0 1 2 3
6 521 3 0 2 3
7 978 3 1 3 1
8 260 2 2 0 1
9 892 0 3 0 1
data
df1 <- structure(list(ID = c(314L, 820L, 223L, 915L, 542L, 521L, 978L,
260L, 892L), Col1 = c(3L, 1L, 1L, 1L, 1L, 4L, 4L, 3L, 1L), Col2 = c(4L,
3L, 1L, 3L, 2L, 1L, 2L, 3L, 4L), Col3 = c(4L, 1L, 3L, 4L, 3L,
3L, 4L, 1L, 1L), Col4 = c(3L, 2L, 1L, 4L, 4L, 4L, 2L, 2L, 2L)),
class = "data.frame", row.names = c(NA,
-9L))