extract lines from a list

when I try to grep the last line of this list, R returns all the lines in the list, is there a way to make R only grep the last line in this example?

  stringlines<-as.list(c("Total des actifs immobilisés 350 952","Total des actifs non courants 357 268",
               "Total des actifs courants 4 324 646",
               "Total des actifs 4 682 115"))
  
  
  stringlines[grep("Total des actifs",stringlines,fixed = T)]
#> [[1]]
#> [1] "Total des actifs immobilisés 350 952"
#> 
#> [[2]]
#> [1] "Total des actifs non courants 357 268"
#> 
#> [[3]]
#> [1] "Total des actifs courants 4 324 646"
#> 
#> [[4]]
#> [1] "Total des actifs 4 682 115"

Created on 2021-05-18 by the reprex package (v1.0.0.9002)

i found a solution

stringlines[grep("Total des actifs",stringlines,fixed = T)][length(stringlines[grep("Total des actifs",stringlines,fixed = T)])]

stringlines <- as.list(c(
  "Total des actifs immobilisés 350 952", "Total des actifs non courants 357 268",
  "Total des actifs courants 4 324 646",
  "Total des actifs 4 682 115"
))

# if index of last element is known
stringlines[[4]]
#> [1] "Total des actifs 4 682 115"

# otherwise
stringlines[[length(stringlines)]]
#> [1] "Total des actifs 4 682 115"

# use to return index match
grep("Total des actifs",stringlines[[4]],fixed = TRUE)
#> [1] 1

# use to extract that match only
stringlines[[4]][grep("Total des actifs",stringlines[[3]],fixed = TRUE)]
#> [1] "Total des actifs 4 682 115"

# simpler
library(magrittr)
if(stringlines[[4]] %>% grep("Total des actifs",.,fixed = TRUE)) stringlines[[4]] else print("not found")
#> [1] "Total des actifs 4 682 115"

As of R4;.10.0, the new |> operator can be used in lieu of %>% and the magrittr library will be unnecessary in this example.

This topic was automatically closed 21 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.