简体   繁体   中英

How to compute a column that depends on a function that uses the value of a variable of each row?

This is a mock-up based on mtcars of what I would like to do:

  • compute a column that counts the number of cars that have less
    displacement ( disp ) of the current row within the same gear type
    category ( am )
  • expected column is the values I would like to get
  • try1 is one try with the findInterval function, the problem is that I cannot make it count across the subsets that depend on the category ( am )

I have tried solutions with *apply but I am somehow never able to make the function called work only on a subset that depends on the value of a variable of the row that is processed (hope this makes sense).

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

Any solution will do; the use of the findInterval function is not mandatory.

I'd rather have a more general solution enabling a column value to be computed by calling a function that takes values from the current row to compute the expected value.

As pointed out by @dimitris_ps, the previous solution neglects the duplicated counts. Following provides the remedy.

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

or

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

Based on @Khashaa's logic this is my approach

library(dplyr)
mtcars %>% 
  group_by(am) %>%
  mutate(expected=match(disp, sort(disp))-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM