I want to use tidyverse
to take a dataframe df
and replace all non-zero values to a value of 1.
Asked
Active
Viewed 2.9k times
-6

I Del Toro
- 913
- 4
- 15
- 36
-
6So greater than zero or non-zero? And please provide a clear [reproducible example](https://stackoverflow.com/q/5963269/1320535) without screenshots. – Julius Vainora Jan 16 '19 at 23:40
3 Answers
15
The following will convert all non-zero numeric values to 1:
df.richness %>% mutate_if(is.numeric, ~1 * (. != 0))
while
df.richness %>% mutate_if(is.numeric, ~1 * (. > 0))
will do that with those greater than zero.

Julius Vainora
- 47,421
- 9
- 90
- 102
9
Alternatively, if you had only numeric data in the dataframe e.g. with sites as the rownames, this would be a simple way without the tidyverse.
df.richness[df.richness > 0] <- 1

A.Elsy
- 128
- 1
- 7
0
We can also convert to logical, then back to numeric:
library(dplyr)
df %>% mutate(across(where(is.numeric), ~+as.logical(.x)))
num1 logical1 num2 char1
1 1 TRUE 0 a
2 1 TRUE 1 b
3 1 TRUE 1 c
4 0 TRUE 1 d
5 1 FALSE 1 e
6 1 FALSE 1 f
7 0 FALSE 0 g
8 1 FALSE 1 h
data
structure(list(num1 = c(1, 2, 3, 0, 1, 99, 0, 2), logical1 = c(TRUE,
TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE), num2 = c(0, 6,
7, 8, 9, 10, 0, 1), char1 = c("a", "b", "c", "d", "e", "f", "g",
"h")), class = "data.frame", row.names = c(NA, -8L))
num1 logical1 num2 char1
1 1 TRUE 0 a
2 2 TRUE 6 b
3 3 TRUE 7 c
4 0 TRUE 8 d
5 1 FALSE 9 e
6 99 FALSE 10 f
7 0 FALSE 0 g
8 2 FALSE 1 h

GuedesBF
- 8,409
- 5
- 19
- 37