Hi,
Thanks, your method does indeed work. Thank you.
Last night, I worked out something similar and found out about rowMeans as well.
Kind wishes,
Ian

yy <- read.table( header = T, sep=",", text =
"Q20, Q21, Q22, Q23, Q24
 0,1, 2,3,4
 1,NA,2,3,4
 2,1, 2,3,4
 5,NA,3,NA,NA")
 yy
  Q20 Q21 Q22 Q23 Q24
1   0   1   2   3   4
2   1  NA   2   3   4
3   2   1   2   3   4
4   5  NA   3  NA  NA
+ yy
yy
x
+  x <- transform( yy,
+   mySum   = rowSums(yy[ ,c("Q20","Q21","Q23")], na.rm=T),
+ myCount = as.numeric(!is.na(Q20))+as.numeric(!is.na(Q21))+as.numeric(!is.na(Q24)),
+   myMean  = rowMeans(yy[ ,c("Q20","Q21","Q23")], na.rm=T)
+ )
+ x
  Q20 Q21 Q22 Q23 Q24 mySum myCount   myMean
1   0   1   2   3   4     4       3 1.333333
2   1  NA   2   3   4     4       2 2.000000
3   2   1   2   3   4     6       3 2.000000
4   5  NA   3  NA  NA     5       1 5.000000
>

However, if there is NA in first column read then rowSums gives an error. I think that is what is happening. How do I solve that?

+ yy <- read.table( header = T, sep=",", text =
+ "Q20, Q21, Q22, Q23, Q24
+  0,1, 2,3,4
+  1,NA,2,3,4
+  NA,1, 2,3,4
+  5,NA,3,NA,NA")
+  yy

  Q20 Q21 Q22 Q23 Q24
1   0   1   2   3   4
2   1  NA   2   3   4
3  NA   1   2   3   4
4   5  NA   3  NA  NA
+ rm(x)
+ x <- transform( yy, ############ Example 6
+   mySum   = rowSums(yy[ ,c("Q20","Q21","Q23")], na.rm=T),
+ myCount = as.numeric(!is.na(Q20))+as.numeric(!is.na(Q21))+as.numeric(!is.na(Q24)),
+   myMean  = rowMeans(yy[ ,c("Q20","Q21","Q23")], na.rm=T)
+ )
Error in rowSums(yy[, c("Q20", "Q21", "Q23")], na.rm = T) :
  'x' must be numeric
Calls: transform -> transform.data.frame -> eval -> eval -> rowSums
> yy

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to