[R] Can't compute row means of two columns of a dataframe.
Bert Gunter
bgunter@4567 @end|ng |rom gm@||@com
Sat Jun 8 19:47:50 CEST 2024
Use apply(), not by().
xxxz$av20 <- apply(xxxz[,c("Low20","High20")],1, mean)
-- Bert
On Sat, Jun 8, 2024 at 10:38 AM Sorkin, John <jsorkin using som.umaryland.edu>
wrote:
> I have a data frame with three columns, TotalInches, Low20, High20. For
> each row of the dataset, I am trying to compute the mean of Low20 and
> High20.
>
> xxxz <- structure(list(TotalInches =
> c(58, 59, 60, 61, 62, 63, 64, 65,
> 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76), Low20 =
> c(84, 87,
> 90, 93, 96, 99, 102, 106, 109, 112, 116, 119, 122, 126,
> 129,
> 133, 137, 141, 144), High20 = c(111, 115, 119, 123,
> 127, 131,
> 135, 140, 144, 148, 153, 157, 162, 167, 171, 176, 181,
> 186, 191
> )), class = "data.frame", row.names = c(NA, -19L))
> xxxz
> str(xxxz)
> xxxz$Average20 <- by(xxxz[,c("Low20","High20")],xxxz[,"TotalInches"],mean)
> warnings()
>
> When I run the code above, I don't get the means by row. I get the
> following warning messages, one for each row of the dataframe.
>
> Warning messages:
> 1: In mean.default(data[x, , drop = FALSE], ...) :
> argument is not numeric or logical: returning NA
> 2: In mean.default(data[x, , drop = FALSE], ...) :
> argument is not numeric or logical: returning NA
>
> Can someone tell my what I am doing wrong, and how I can compute the row
> means?
>
> Thank you,
> John
>
> John David Sorkin M.D., Ph.D.
> Professor of Medicine, University of Maryland School of Medicine;
> Associate Director for Biostatistics and Informatics, Baltimore VA Medical
> Center Geriatrics Research, Education, and Clinical Center;
> PI Biostatistics and Informatics Core, University of Maryland School of
> Medicine Claude D. Pepper Older Americans Independence Center;
> Senior Statistician University of Maryland Center for Vascular Research;
>
> Division of Gerontology and Paliative Care,
> 10 North Greene Street
> GRECC (BT/18/GR)
> Baltimore, MD 21201-1524
> Cell phone 443-418-5382
>
>
>
> ______________________________________________
> R-help using 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list