如何查找数据框的行均值包括分类变量。汇总类别组的数字数据?

how to find row Means of a data frame includes categorical variables. summing up numeric data of a category group?

一个青霉素产量的数据,包括四个处理(A,B,C,D)'our columns'和五个block'row'。 我需要分别计算每行的总和和平均值。 dataframe 在 col 中引入了变量,我无法定义处理 A 的变量并对其进行总结。我想知道如何按照每行中有 4 个数字的方式编写它们,以便计算其均值和总和...

这是我的代码:

pencilline=c(89,88,97,94,84,77,92,79,81,87,87,85,87,92,89,84,79,81,80,88)
treatment=factor(rep(LETTERS[1:4],times=5))
block=sort(rep(1:5,times=4))
datap=data.frame(pencilline,block,treatment)
datap
 
datap_subset=unlist(lapply(datap,is.numeric))
datap_subset
pencilline      block  treatment 
      TRUE       TRUE      FALSE 
rowMeans(datap[,datap_subset])
 [1] 45.0 44.5 49.0 47.5 43.0 39.5 47.0 40.5 42.0 45.0 45.0 44.0 45.5 48.0 46.5 44.0 42.0 43.0 42.5 46.5

给出错误的 rowMeans。

你想要这个吗?

library(dplyr)
datap %>% group_by(block) %>%
  summarise(mean = mean(pencilline))

# A tibble: 5 x 2
  block  mean
  <int> <dbl>
1     1    92
2     2    83
3     3    85
4     4    88
5     5    82

它的 baseR 等价物

aggregate(pencilline ~ block, datap, mean)

  block pencilline
1     1         92
2     2         83
3     3         85
4     4         88
5     5         82