[英]Replace values greater than zero with 1 in r
以下將所有非零數值轉換為 1:
df.richness %>% mutate_if(is.numeric, ~1 * (. != 0))
盡管
df.richness %>% mutate_if(is.numeric, ~1 * (. > 0))
將對那些大於零的人這樣做。
或者,如果數據框中只有數字數據,例如以站點作為行名,這將是一種沒有 tidyverse 的簡單方法。
df.richness[df.richness > 0] <- 1
我們也可以轉換為邏輯,然后再轉換回數字:
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
數據
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.