[英]How to add calculated row based on mulitple column and row values in r in?
If I have a dataframe below and I want to add another row for each group in r:如果我在下面有一个数据框并且我想为 r 中的每个组添加另一行:
dataframe before:之前的数据框:
Letter Value
A 1
A 2
A 3
B 1
B 2
B 3
If I just wanted to add another row for each group that averaged those rows, how would I go about that:如果我只想为平均这些行的每个组添加另一行,我将如何处理:
dataframe after:之后的数据帧:
Letter Value
A 1
A 2
A 3
A 2
B 1
B 2
B 3
B 2
A base R solution could be基本的 R 解决方案可能是
do.call(rbind, lapply(split(df, df$Letter),
function(x) rbind(x, c(unique(x$Letter), mean(x$Value)))))
# Letter Value
#A.1 A 1
#A.2 A 2
#A.3 A 3
#A.4 A 2
#B.4 B 1
#B.5 B 2
#B.6 B 3
#B.41 B 2
This requires column Letter
to be a character
vector.这要求Letter
列是一个character
向量。 If Letter
is a factor
you can convert from factor
to character
vector如果Letter
是一个factor
您可以从factor
转换为character
向量
df$Letter <- as.character(df$Letter)
df <- read.table(text =
"Letter Value
A 1
A 2
A 3
B 1
B 2
B 3", header = T, stringsAsFactors = FALSE)
Calculate the mean of value by letter giving ag
, rbind that to the end of DF
giving DF2
and sort.通过给出ag
的字母计算值的平均值,将其绑定到给出DF2
的DF
的末尾并排序。
ag <- aggregate(value ~ letter, DF, mean)
DF2 <- rbind(DF, ag)
o <- order(DF2$letter, rownames(DF2))
DF2[o, ]
giving:给予:
letter value
1 A 1
2 A 2
3 A 3
7 A 2
4 B 1
5 B 2
6 B 3
8 B 2
The input DF
in reproducible form is:可重现形式的输入DF
是:
DF <- data.frame(letter = rep(c("A", "B"), each = 3), value = 1:3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.