conditional sum with starts_with in R

Hi, i am currently working on a dataset which has the following structure :

structure(list(code = c(NA, "613506", "651001", "615500", "615505", 
"615506"), compte = c("Servicios exteriores", "6210010006 LOCATION FAIBLE VALEUR À 
LONG TERME", 
"6210030000 REDEVANCES POUR LICENCES", "6220000000 REPARATION IMMEUBLE, 
INSTALLATIONS ET MACHINES", 

"6220000002 REPARATIONS MACHINES", "6220000003 REPARATION MOBILIERE, PEINTURE
ET DECORATION"
), montant = c(0, 11516.63, 3733.12, 150.72, 0, 2.75)), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

I want to sum the values in the second column according to the values of the first column (but only the first 3 digits, not the whole value), using the starts_with() function. I have run the following code :

 sum(col_test[which(col_test[,1] == starts_with(606)),2])

yet it doesn't work as 606 is numeric and not a character. How can i proceed ?

I think you mean to use the startsWith() function of base R and not the starts_with() function of dplyr. Also, summing the second column does not make sense. I assume you mean the third column. Try

sum(col_test[startsWith(col_test$code,"606"),3], na.rm = TRUE)

works perfectly, thanks a lot !

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.