Tuesday, 15 May 2012

r - replace Logical,0 with 0 -



r - replace Logical,0 with 0 -

i attempted reply question: create vectors containing 0 or 1 based on subjects in r got far next line of code, returns matrix named 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

assuming started matrix pollution, how can convert matrix of 1's , 0's:

# subject.1 subject.2 subject.3 # [1,] 1 0 0 # [2,] 0 1 0 # [3,] 0 0 1 # [4,] 0 0 1

i have answered several questions on stack overflow regarding how replace na's 0's, etc. however, cannot figure out how replace these logical,0's.

for example:

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

thank advice. sorry if duplicate. searching word logical returns lot of hits.

may helps:

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

or

matrix((!sapply(pollution, is.logical))+0,4)

r logical

No comments:

Post a Comment