mercredi 25 novembre 2020

Delete rows in matrix based on two conditions

I have a vector p of countries and a matrix Z of countries. Some countries in Z are not included in p. I would like an argument that has two if's: delete countries from Z if they are not included in p AND if they also have only NA's or 0's in Z (i.e. rowsums in Z = 0). They should only be deleted if both if's apply.

Here is an example of the data. In the expected output, the third row should be deleted, since it has 0 in both the vector and the matrix.

p <- c(2769, 93893300, 0, 4550430, 0) #vector

Z <- read.table(header=FALSE, 
                text="0 138201.333333333    0   0   0
0   1162.33333333333    0   38.3333333333333    0
0   0   0   0   0
0   300238  0   9675    0
0   93  0   0   0
")  #matrix

I attempted to do this by: Zsubsetted <- subset(Z, !(p == "NA" & rowSums(Z) == "0"))

but this does not work. Any suggestions?

Aucun commentaire:

Enregistrer un commentaire