简体   繁体   中英

R and dplyr: Creating a new column that divides values by multiple maximal values of another column

I am editing a dataframe using dplyr where I have information on multiple reaction times(rt) for different individuals(id). I now want to make a new column, where I divide each specific reaction time by the individual's maximum reaction time. Currently, I have only managed to divide each specific reaction time by the maximum reaction time of the group, using the following code:

df <- mutate(df, spcRT=rt)
df <- group_by(df, id, rt) %>% summarise(
      spcRT = max(df$rt, na.rm=TRUE) ) %>% as.data.frame()
 which(is.na(df))

df <- mutate(df,IDspcRT = rt/spcRT)

If we need to create a column ('spcRT') by dividing the reaction time ('rt') with the maximum reaction time ( max(rt, na.rm=TRUE) ) for each 'id', then we need to group by 'id' and do the division.

 df %>%
    group_by(id) %>%
    mutate(spcRT = rt/max(rt, na.rm=TRUE))

It is not clear why the OP used 'rt' along with 'id' as grouping variable in the post. It would give only a single unique 'rt' value and there is no need for any max .

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