我试图回答这个问题:Create vectors containing 0 or 1 based on subjects in R
我只得到以下代码行,它返回一个名为matrix
的{{1}}:
pollution
假设我开始使用pollution <- apply(mydf[,2:4], c(1,2), function(i) {
ifelse(grep('POLLUTION|EMISSION|WASTE',i)==1,1,0)} )
pollution
# SUBJECT.1 SUBJECT.2 SUBJECT.3
# [1,] 1 Logical,0 Logical,0
# [2,] Logical,0 1 Logical,0
# [3,] Logical,0 Logical,0 1
# [4,] Logical,0 Logical,0 1
matrix
,我该如何将其转换为pollution
matrix
和1
的:{/ p>
0
我已经回答了有关如何将# SUBJECT.1 SUBJECT.2 SUBJECT.3
# [1,] 1 0 0
# [2,] 0 1 0
# [3,] 0 0 1
# [4,] 0 0 1
替换为NA
等的Stack Overflow的几个问题。但是,我无法弄清楚如何替换这些0
的。
例如:
Logical,0
感谢您的任何建议。对不起,如果这是重复的。搜索单词pollution[is.logical(pollution)] = 0
# SUBJECT.1 SUBJECT.2 SUBJECT.3
# [1,] 1 Logical,0 Logical,0
# [2,] Logical,0 1 Logical,0
# [3,] Logical,0 Logical,0 1
# [4,] Logical,0 Logical,0 1
pollution2 <- as.data.frame(pollution)
pollution2
# SUBJECT.1 SUBJECT.2 SUBJECT.3
# 1 1
# 2 1
# 3 1
# 4 1
会返回大量点击。
答案 0 :(得分:3)
这是我能想到的最容易的:
pollution2 <- pollution
pollution2[] <- as.numeric(sapply(pollution, function(x) length(x) > 0))
pollution2
SUBJECT.1 SUBJECT.2 SUBJECT.3
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[4,] 0 0 1
请注意我如何使用[]
表示法保留矩阵结构和dimnames。
编辑:对apply
的调整非常简单,仅供参考
apply(mydf[,2:4], c(1,2), function(i) {
ifelse(length(grep('POLLUTION|EMISSION|WASTE',i)),1,0)} )
SUBJECT.1 SUBJECT.2 SUBJECT.3
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[4,] 0 0 1
答案 1 :(得分:3)
可能这也有帮助:
matrix(sapply(c(pollution),length),4)
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[4,] 0 0 1
或
matrix((!sapply(pollution, is.logical))+0,4)
答案 2 :(得分:2)
我知道我可以这样做:
> new.pollution <- matrix(as.numeric(pollution), nrow=4, byrow=FALSE)
> new.pollution[is.na(new.pollution)] = 0
> new.pollution
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[4,] 0 0 1
但肯定有一种更简单的方法。