将R中多个列的所有正计数赋值为1
我有一个如下所示的数据表:将R中多个列的所有正计数赋值为1,r,data.table,R,Data.table,我有一个如下所示的数据表: library(data.table) Well <- c("A1", "A2", "A3", "A4", "A5") Episyrphus <- c(0,0,5,3,1) Eupeodes <- c(2,0,4,1,0) Syrphus <- c(0,4,0,3,2) dt <- data.table(Well, Episyrphus, Eupeodes, Syrphus) dt Well Episyrphus Eupeod
library(data.table)
Well <- c("A1", "A2", "A3", "A4", "A5")
Episyrphus <- c(0,0,5,3,1)
Eupeodes <- c(2,0,4,1,0)
Syrphus <- c(0,4,0,3,2)
dt <- data.table(Well, Episyrphus, Eupeodes, Syrphus)
dt
Well Episyrphus Eupeodes Syrphus
1: A1 0 2 0
2: A2 0 0 4
3: A3 5 4 0
4: A4 3 1 3
5: A5 1 0 2
但是,我的问题是,我无法在多个列中将非零替换为1。我为一个专栏找到的解决方案是:
dt[Episyrphus > 0, Episyrphus := 1L]
但是,有没有办法使用相同的代码结构(可能带有for循环(?)来跨所有种类列执行相同的功能
我觉得答案很明显,但对我来说不是!任何帮助都将不胜感激。你可以做到
cols <- seq(ncol(dt))[-1]
dt[ , (cols) := lapply(.SD, as.logical), .SDcols = cols]
cols这是一种dplyr
方法
dt %>% dplyr::mutate_if(is.numeric, funs(sign(.)))
# Well Episyrphus Eupeodes Syrphus
# 1 A1 0 1 0
# 2 A2 0 0 1
# 3 A3 1 1 0
# 4 A4 1 1 1
# 5 A5 1 0 1
适当的数据类型是逻辑的。如果必须是整数,则可以从逻辑值轻松创建它们ifelse
效率低下,应始终避免使用dt[,2:4:=lappy(.SD,as.logical),.SDcols=2:4]
Point take:)我想这个问题的关键是如何在列的子集上应用转换。我会采纳你的建议。在效率方面可能不会更好,但还有replace(x,x!=0,1L)
——对我来说更容易理解。顺便说一句,您使用cols
,但不首先定义它。重新“在列的子集上应用转换”,q在这里:对不起,重复的问题,我没有找到前面引用的问题。
dt %>% dplyr::mutate_if(is.numeric, funs(sign(.)))
# Well Episyrphus Eupeodes Syrphus
# 1 A1 0 1 0
# 2 A2 0 0 1
# 3 A3 1 1 0
# 4 A4 1 1 1
# 5 A5 1 0 1