问题描述
我有一个包含丰度变量的数据集,其中数据是有序的(0、1-5、6-10、10+),但我需要将其转换为存在/不存在数据(0 或 1)。我该怎么做?
这是数据:
'data.frame': 100 obs. of 3 variables:
$ date : Date,format: "2021-02-11" "2021-02-15" "2021-02-16" "2021-02-15" ...
$ abund : Factor w/ 4 levels "0","1-5","6-10",..: 4 1 3 3 4 1 4 2 1 3 ...
$ postcode: chr "EH12 7ET" "NW1 1HP" "TA21 0AS" "LE7 3SY" ...
解决方法
your_data$abund <- ifelse(your_data$abund=="0",1)
或
your_data$abund <- as.numeric(your_data$abund!="0")
后者有效,因为 as.numeric()
将 FALSE
转换为 0,将 TRUE
转换为 1。
或使用 transform(your_data,abund=...)
(基本 R)或 your_data %>% mutate(across(abund,~1-as.numeric(.=="0))
或 ...