Hi Petra, Try this: dat$sums <- rowSums(dat[3:5], na.rm=TRUE)
I think this should do what you're looking for HTH, Ivan -------- Message original -------- Sujet: [R] Sum of a couple of variables of which a few have NA values Date : Tue, 10 Jan 2012 17:25:21 +0100 De : Petra Opic <petrao...@gmail.com> Pour : r-help@r-project.org Dear everyone, I have looked all over the internet but I cannot find a way to solve my problem. In my data I want to sum a couple of variables. Some of these variables have NA values, and when I add them together, the result is NA dat<- data.frame( id = gl(5,1), var1 = rnorm(5, 10), var2 = rnorm(5, 7), var3 = rnorm(5, 6), var4 = rnorm(5, 3), var5 = rnorm(5, 8) ) dat[3,3]<- NA dat[4,5]<- NA
dat
id var1 var2 var3 var4 var5 1 1 9.371328 7.830814 5.032541 3.491053 7.626418 2 2 10.413516 7.333630 6.557178 1.465597 8.591770 3 3 10.967073 NA 6.674079 3.946451 7.251263 4 4 9.900380 7.727111 5.059698 NA 6.632962 5 5 9.191068 7.901271 6.652410 2.734856 8.484757 attach(dat) dat$sum<- var2 + var3 + var4 # I think I'm doing this wrong, but I don't know what command to use
dat
id var1 var2 var3 var4 var5 sum 1 1 9.371328 7.830814 5.032541 3.491053 7.626418 16.35441 2 2 10.413516 7.333630 6.557178 1.465597 8.591770 15.35640 3 3 10.967073 NA 6.674079 3.946451 7.251263 NA 4 4 9.900380 7.727111 5.059698 NA 6.632962 NA 5 5 9.191068 7.901271 6.652410 2.734856 8.484757 17.28854 I would like to omit the values of NA and just sum the rest. I tried to use rowSums() but that sums an entire row and I only need a few variables. Does anyone know how to do this? Thanks in advance, Petra ______________________________________________ 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. -- Ivan CALANDRA Université de Bourgogne UMR CNRS 5561 Biogéosciences 6 Boulevard Gabriel 21000 Dijon, FRANCE ivan.calan...@u-bourgogne.fr ______________________________________________ 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.