r - 根据其他列减去该列的最小值

标签 r dataframe tapply

我有一个数据框如下:

 d

  year total  file
  1999        3931.12000 A
  2002        4273.71020 A
  2005        4601.41493 A
  2008        4101.32100 A
  1999         346.82000 B
  2002         134.30882 B
  2005         130.43038 B
  2008          88.27546 B

我希望每个组中的总和及其最小值的差异由文件确定。
我可以想到通过以下方式获得最低限度:

 tapply(d$total, d$file, min)

但我想不出获得减去最小值的向量的明智方法。

最佳答案

我建议使用 withinave。像这样:

within(mydf, {
  tot2 <- ave(total, file, FUN = function(x) x - min(x))
})
#   year      total file      tot2
# 1 1999 3931.12000    A   0.00000
# 2 2002 4273.71020    A 342.59020
# 3 2005 4601.41493    A 670.29493
# 4 2008 4101.32100    A 170.20100
# 5 1999  346.82000    B 258.54454
# 6 2002  134.30882    B  46.03336
# 7 2005  130.43038    B  42.15492
# 8 2008   88.27546    B   0.00000

或者,使用“data.table”:

library(data.table)
DT <- data.table(mydf)
DT[, tot2 := total - min(total), by = file][]

或者,使用“dplyr”:

library(dplyr)
mydf %>% group_by(file) %>% mutate(tot2 = total - min(total))

关于r - 根据其他列减去该列的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24979757/

相关文章:

r - do_one(nmeth) 错误 : NA/NaN/Inf in foreign function call (arg 1)

r - 如何将用户定义的图例添加到 R 中的 ggplot?

python - 结合 Pandas 的 startwith 和 isin

python - 如何选择列标题中的 nan

如果大于 0, Pandas 数据框会更改所有值

r - 单个 tapply 或聚合语句中的多个函数

r - 使用 tapply 按组对多列求和

R:使用 ggplot2 运行总计的聚集列

r - 向大型 (16Mill) 列表的所有元素添加一些字符串(可能是关于应用语法的问题)

R 函数 which.max with tapply