change the values of selected columns

i want to replace all values greater than 0 to 0 and all the values equal to 0 to 1. i am able to convert one by one but what is the best and easiest way in single line of code ..?

i have tried the below approach but its changing everything to 0 or everything to 1

df <- data.frame(cc=c(1,NA,3,NA,4,NA,23,17,NA,0),
                 bb=c(0,NA,12,NA,2,0,NA,12,14,0),
                 dd=c(12,0,0,NA,3,0,NA,23,7,9))


df1 <- df %>% mutate(across(c(cc, bb,dd), ~replace(., .>0, 0)),across(c(cc, bb,dd), ~replace(., .=0, 1)))

the overall objective is to replace values greater than 0 to 0 and values equals to 0 to 1

image

this code achieves the explicit target;

df |> mutate(
  across(everything(),
         \(x)if_else(x>0,0,1))
)

i.e. it seems sufficient to make everything bigger than 0 to be 0 , and anything else to 1
This code may need changes if your data could contain negative numbers.

if i wanted to exclude last column ..???
or if i wanted to mutate the selected columns then...??

change everything() to the choice of columns that you want to do it for.
like in your original code across(c(cc, bb,dd)

To change everything in place (mutate in dplyr parlance)

d <- data.frame(cc=c(1,NA,3,NA,4,NA,23,17,NA,0),
                 bb=c(0,NA,12,NA,2,0,NA,12,14,0),
                 dd=c(12,0,0,NA,3,0,NA,23,7,9))

d
#>    cc bb dd
#> 1   1  0 12
#> 2  NA NA  0
#> 3   3 12  0
#> 4  NA NA NA
#> 5   4  2  3
#> 6  NA  0  0
#> 7  23 NA NA
#> 8  17 12 23
#> 9  NA 14  7
#> 10  0  0  9
d[d == 0] <- 1
d[!is.na(d) & d != 1] <- 0
d
#>    cc bb dd
#> 1   1  1  0
#> 2  NA NA  1
#> 3   0  0  1
#> 4  NA NA NA
#> 5   0  0  0
#> 6  NA  1  1
#> 7   0 NA NA
#> 8   0  0  0
#> 9  NA  0  0
#> 10  1  1  0

Created on 2023-09-19 with reprex v2.0.2

To exclude the last column, the clearest is to use a temporary split

d <- data.frame(cc=c(1,NA,3,NA,4,NA,23,17,NA,0),
                 bb=c(0,NA,12,NA,2,0,NA,12,14,0),
                 dd=c(12,0,0,NA,3,0,NA,23,7,9))

e <- d[3]
d <- d[1:2]
d[d == 0] <- 1
d[!is.na(d) & d != 1] <- 0
d <- cbind(d,e)
d
#>    cc bb dd
#> 1   1  1 12
#> 2  NA NA  0
#> 3   0  0  0
#> 4  NA NA NA
#> 5   0  0  3
#> 6  NA  1  0
#> 7   0 NA NA
#> 8   0  0 23
#> 9  NA  0  7
#> 10  1  1  9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.