另一列的不同值的列的总和

时间:2017-02-17 09:59:30

标签: r

我有以下数据框:

d <- data.frame(x = c(6,6,6,17,17,17,68,68,68), w = c(4,2,1,0,5,1,0,2,7))

现在我想添加一个新列sw,以便

    每个x=6sw=4+2+1+0+5+1+0+2+7=22

  • 每个x=17sw=0+5+1+0+2+7=15

  • 每个x=68sw=0+2+7=9

即,

d
   x w sw
1  6 4 22
2  6 2 22
3  6 1 22
4 17 0 15
5 17 5 15
6 17 1 15
7 68 0  9
8 68 2  9
9 68 7  9

对于此示例,我可以执行以下操作:

j = sum(d$w)
k = sum(d$w[d$x!=6])
l = sum(d$w[d$x==68])

d$sw <- c(rep(j,3),rep(k,3),rep(l,3))

但对于x的100个不同值,我无法进行此类编码,即使我可能不知道x采用了什么值,因为我将生成x=round(rexp(1000,1/100))

3 个答案:

答案 0 :(得分:2)

我们可以使用function UpdateUserDetails() { var title = $("#title1").val(); var store = $(".search-box").val(); var category= $("#category").val(); var descp=$("#descp1").val(); var price=$("#price1").val(); var value=$("#value1").val(); var location=$("#location1").val(); var url=$("#url1").val(); var id = $("#hidden_user_id").val(); $.post("update.php", { id: id, title:title, store:store, category:category, descp:descp, price:price, value:value, location:location, url:url }, function (data, status) { $("#update_user_modal").modal("hide"); } ); }

执行此操作
base R

答案 1 :(得分:2)

另一个想法是通过基础R使用带有Reduce参数的accumulate = TRUE,即

ind <- aggregate(w ~ x, d, length)$w #get lengths of each group
rslts <- rev(unlist(lapply(Reduce(`rbind`, rev(split(d, d$x)), accumulate = TRUE), 
                                                                 function(i) sum(i$w))))
d$sw <- rep(rslts, ind)

d
#   x w sw
#1  6 4 22
#2  6 2 22
#3  6 1 22
#4 17 0 15
#5 17 5 15
#6 17 1 15
#7 68 0  9
#8 68 2  9
#9 68 7  9

答案 2 :(得分:1)

这是第三个基本R解决方案,首先计算值,然后将它们合并到原始data.frame。

merge(df, within(aggregate(w ~ x, data=df, sum), sw <- rev(cumsum(rev(w))))[-2], by="x")
   x w sw
1  6 4 22
2  6 2 22
3  6 1 22
4 17 0 15
5 17 5 15
6 17 1 15
7 68 0  9
8 68 2  9
9 68 7  9

aggregate(w ~ x, data=df, sum)计算每个x组的w之和,然后sw <- rev(cumsum(rev(w)))首先使用两个revs创建累积和以获得正确的计算,然后将其按正确的顺序排列。这些函数包含在within中,因此会返回此data.frame的副本,[-2]会删除由aggregate计算的现在无关的w项。然后将此聚合的data.frame合并到原始data.frame。

数据

df <- 
structure(list(x = c(6L, 6L, 6L, 17L, 17L, 17L, 68L, 68L, 68L
), w = c(4L, 2L, 1L, 0L, 5L, 1L, 0L, 2L, 7L)), .Names = c("x", 
"w"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"
), class = "data.frame")