Summation by groups, but exclude values ​​below the designated identifier

I am trying to move from this:

#Starting df
name = c("tom", "tom", "tom", "chris", "chris", "chris", "jen", "jen", "jen") 
value = c(2,10,"end",45,"end",13,6,"end",13) 
df = data.frame(name,value) 

or this (which uses NA as a cutoff)

#Starting df
name = c("tom", "tom", "tom", "chris", "chris", "chris", "jen", "jen", "jen") 
value = c(2,10,NA,45,NA,13,6,NA,13) 
starting_df = data.frame(name,value) 

For this:

#Ending df
name = c("tom", "tom", "tom", "chris", "chris", "chris", "jen", "jen", "jen") 
value = c(12,12,12,45,45,45,6,6,6) 
ending_df = data.frame(name,value) 

The idea here is to summarize by group (name in this case), which I can easily use with the function group_byfrom dplyr, but I need to delete all the values ​​below NAsor the text that reads end. Values ​​below these cutoffs cannot be included in my amount. I have been working on this all night and I'm not up to date. Thank you for your help.

+4
source share
2 answers

"" "" numeric ( character, factor, as.numeric(as.character(value))), NA, NA which is.na sum ' ,

starting_df %>%
    group_by(name) %>%
    mutate(value = as.numeric(value), 
           value = sum(value[seq_len(which(is.na(value))[1])], na.rm = TRUE))
# A tibble: 9 x 2
# Groups:   name [3]
#    name value
#  <fctr> <dbl>
#1    tom    12
#2    tom    12
#3    tom    12
#4  chris    45
#5  chris    45
#6  chris    45
#7    jen     6
#8    jen     6
#9    jen     6
+2

R ave, (name) , NA which.max sum values .

starting_df$value <- ave(starting_df$value, starting_df$name, FUN = function(x) 
                                sum(x[1:which.max(is.na(x)) - 1]))

starting_df

#   name value
#1   tom    12
#2   tom    12
#3   tom    12
#4 chris    45
#5 chris    45
#6 chris    45
#7   jen     6
#8   jen     6
#9   jen     6

@thelatemail, , cumsum. cumsum , NA s.

starting_df$value <- ave(starting_df$value, starting_df$name, FUN = function(x) 
                              max(cumsum(x), na.rm = TRUE))
+2

Source: https://habr.com/ru/post/1688984/


All Articles