我有一个数据框:
head(Diets)
Sp1 Sp2 Sp3 Sp4 Sp5
1 0.4 0.4 0.1 0.2 0.0
2 1.4 0.1 0.1 0.3 3.4
3 0.5 0.6 0.1 0.4 0.0
....
我想创建一个新的数据框,根据来自其他数据框的成员资格(因子)对这些值进行求和:
head(Groups)
SpName GroupName
1 Sp1 Grp1
2 Sp2 Grp1
3 Sp3 Grp2
4 Sp4 Grp3
5 Sp5 Grp3
....
得到这个:
Grp1 Grp2 Grp3
1 0.8 0.1 0.2
2 1.5 0.1 3.7
3 1.1 0.1 0.4
答案 0 :(得分:2)
您可以使用基础R aggregate
函数
Step1 将data.frames
放在一起data = data.frame(cbind(df1, t(df2)))
Step2 执行与每个组相对应的值的总和
out = aggregate(cbind(X1, X2, X3) ~ V3 , data, sum)
Step3 通过使用setNames
setNames(data.frame(t(out[,-1]),row.names = NULL), out[,1])
# Grp1 Grp2 Grp3
#1 0.8 0.1 0.2
#2 1.5 0.1 3.7
#3 1.1 0.1 0.4
数据强>
df1 = structure(list(V1 = 1:5, V2 = structure(1:5, .Label = c("Sp1",
"Sp2", "Sp3", "Sp4", "Sp5"), class = "factor"), V3 = structure(c(1L,
1L, 2L, 3L, 3L), .Label = c("Grp1", "Grp2", "Grp3"), class = "factor")), .Names = c("V1",
"V2", "V3"), class = "data.frame", row.names = c(NA, -5L))
df2 = structure(list(Sp1 = c(0.4, 1.4, 0.5), Sp2 = c(0.4, 0.1, 0.6),
Sp3 = c(0.1, 0.1, 0.1), Sp4 = c(0.2, 0.3, 0.4), Sp5 = c(0,
3.4, 0)), .Names = c("Sp1", "Sp2", "Sp3", "Sp4", "Sp5"), class = "data.frame", row.names = c("1",
"2", "3"))
答案 1 :(得分:1)
match
如果饮食的名称与组数据的顺序相同,您可以使用它。否则,# names(diets) <- groups$GroupName
names(diets) <- groups$GroupName[match(names(diets), groups$SpName)]
sapply(split(names(diets), names(diets)), function(x)
rowSums(diets[, names(diets) %in% x, drop = FALSE]))
# Grp1 Grp2 Grp3
# 1 0.8 0.1 0.2
# 2 1.5 0.1 3.7
# 3 1.1 0.1 0.4
会更安全
jQuery(document).ready(function ($) {
var slideCount = $('#banner-pagination ul li a').length;
var slideWidth = $('#banner-pagination ul li a').width();
var slideHeight = $('#banner-pagination ul li a').height();
var sliderUlWidth = slideCount * slideWidth;
$('#banner-pagination').css({ width: slideWidth, height: slideHeight });
$('#banner-pagination ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
$('#banner-pagination ul li:last-child').prependTo('#slider ul');
function moveLeft() {
$('#banner-pagination ul').animate({
left: + slideWidth
}, 1000, function () {
$('#banner-pagination ul li:last-child').prependTo('#slider ul');
$('#banner-pagination ul').css('left', '');
});
};
function do_slide(){
interval = setInterval(function(){
moveLeft();
}, 1000);
}
do_slide();
$('ul li').hover(function(){
clearInterval(interval);
});
$('ul li').mouseleave(function(){
do_slide();
});
});