[R] na.action
Tony Plate
tplate at acm.org
Sat Apr 30 00:01:54 CEST 2005
Maybe this does what you want:
> x <- as.matrix(read.table("clipboard"))
> x
V1 V2 V3 V4
1 NA 0 0 0
2 0 NA 0 NA
3 0 0 NA 2
4 0 0 2 NA
> rowSums(x==2, na.rm=T)
1 2 3 4
0 0 1 1
>
There's probably at least 5 or 6 other quite sensible ways of doing
this, but this is probably the fastest (and the least versatile).
A more general building block is the sum() function, as in:
> sum(x[3,]==2, na.rm=T)
[1] 1
>
The key is the use of the 'na.rm=T' argument value.
hope this helps,
Tony Plate
Tim Smith wrote:
> Hi,
>
> I had the following code:
>
> testp <- rcorr(t(datcm1),type = "pearson")
> mat1 <- testp[[1]][,] > 0.6
> mat2 <- testp[[3]][,] < 0.05
> mat3 <- mat1 + mat2
>
> The resulting mat3 (smaller version) matrix looks like:
>
> NA 0 0 0
> 0 NA 0 NA
> 0 0 NA 2
> 0 0 2 NA
>
> To get to the number of times a '2' appears in the rows, I was trying to run the following code:
>
> numrow = nrow(mat3)
> counter <- matrix(nrow = numrow,ncol =1)
> for(i in 1:numrow){
> count = 0;
> for(j in 1:numrow){
> if(mat3[i,j] == 2){
> count = count + 1
> }
> }
> counter[i,1] = count
> }
>
> However, I get the following error:
>
> 'Error in if (mat3[i, j] == 2) { : missing value where TRUE/FALSE needed'
>
> I also tried to use the na.action, but couldn't get anything. I'm sure there must be a relatively easy fix to this. Is there a workaround this problem?
>
> thanks,
>
> Tim
>
>
> __________________________________________________
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list