I have an R dataframe like below with all numeric columns. All non NA values are either greater than/equal to 1 or less than -1. I want to subtract 1 from all the positive values and add 1 to all the negative values, ignoring all the NAs.
My output dataframe should look like below
I know how to replace NAs with zero and vice versa
df[is.na(df)] <- 0
df[df==0] <- NA
I tried something similar for my problem also
df[df >= 1] <- df - 1
df[df < -1] <- df + 1
Getting an error 'value' is the wrong length. Also tried ifelse
df <- ifelse(df >= 1, df - 1, df + 1)
This is subtracting 1 from all values (including negatives). Also tried if and else separately
if(df >= 1){
df <- df - 1
}else if(df < -1){
df <- df + 1
}
This is also subtracting 1 from all. I have programmed in other languages before and relatively new to R. Need help on this. My actual dataframe is having more than 1000 columns.
I found a similar question on stackoverflow, but the answers are using specific column indexes which is not possible in my case.