gpt4 book ai didi

r - 如何计算依赖于使用每行变量值的函数的列?

转载 作者:行者123 更新时间:2023-12-04 10:27:39 25 4
gpt4 key购买 nike

这是一个基于 mtcars 我想做的事情的模型:

  • 计算一列,计算拥有较少汽车的数量
    当前行在同一齿轮类型内的位移 (disp)
    类别()
  • 预期列是我想得到的值
  • try1 是使用 findInterval 函数的一次尝试,问题是我无法让它在依赖于类别的子集中计数(am)

我已经尝试过使用 *apply 的解决方案,但我永远无法使调用的函数仅在一个子集上工作,该子集取决于所处理行的变量值(希望这个说得通)。

x = mtcars[1:6,c("disp","am")]
# expected values are the number of cars that have less disp while having the same am
x$expected = c(1,1,0,1,2,0)
#this ordered table is for findInterval
a = x[order(x$disp),]
a
# I use the findInterval function to get the number of values and I try subsetting the call
# -0.1 is to deal with the closed intervalq
x$try1 = findInterval(x$disp-0.1, a$disp[a$am==x$am])
x
# try1 values are not computed depending on the subsetting of a

任何解决方案都可以; findInterval 函数的使用不是强制性的。

我宁愿有一个更通用的解决方案,通过调用一个函数来计算列值,该函数从当前行获取值以计算预期值。

最佳答案

正如@dimitris_ps 所指出的,之前的解决方案忽略了重复计数。以下提供补救措施。

library(dplyr)
x %>%
group_by(am) %>%
mutate(expected=findInterval(disp, sort(disp) + 0.0001))

library(data.table)
setDT(x)[, expected:=findInterval(disp, sort(disp) + 0.0001), by=am]

关于r - 如何计算依赖于使用每行变量值的函数的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com