简体   繁体   中英

Replace values greater than zero with 1 in r

I want to use tidyverse to take a dataframe df and replace all non-zero values to a value of 1. 在此处输入图片说明

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.

或者,如果数据框中只有数字数据,例如以站点作为行名,这将是一种没有 tidyverse 的简单方法。

df.richness[df.richness > 0] <- 1 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM