[R] Taking the sum of only some columns of a data frame
William Dunlap
wdunlap at tibco.com
Fri Mar 31 19:19:39 CEST 2017
> dat <- data.frame(Group=LETTERS[1:5], X=1:5, Y=11:15)
> pos <- c(2,3)
> rbind(dat, Sum=lapply(seq_len(ncol(dat)), function(i) if (i %in% pos) sum(dat[,i]) else NA_real_))
Group X Y
1 A 1 11
2 B 2 12
3 C 3 13
4 D 4 14
5 E 5 15
Sum <NA> 15 65
> str(.Last.value)
'data.frame': 6 obs. of 3 variables:
$ Group: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5 NA
$ X : int 1 2 3 4 5 15
$ Y : int 11 12 13 14 15 65
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Fri, Mar 31, 2017 at 9:20 AM, Bruce Ratner PhD <br at dmstat1.com> wrote:
> Hi R'ers:
> Given a data.frame of five columns and ten rows.
> I would like to take the sum of, say, the first and third columns only.
> For the remaining columns, I do not want any calculations, thus rending their "values" on the "total" row blank. The sum/total row is to be combined to the original data.frame, yielding a data.frame with five columns and eleven rows.
>
> Thanks, in advance.
> Bruce
>
>
> ______________
> Bruce Ratner PhD
> The Significant Statistician™
>
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
More information about the R-help
mailing list