I am looking for help implementing a function in R to truncate a level_stream
string vector of my dataframe in R and haven't had much luck yet. Essentially when a row in the pre_quiz_score
column is not NA
, I want to truncate the beginning part of the string up until (and including) the first |
character, and I want to truncate everything past the last |
character if a post_quiz_score
is not NA
for that row.
df <- data.frame(ls = c('123 L0=38/42|425 L0=40/42', NA, '482 L7=7/12|789 L8=5/6|523 L9=2/6'),
pre_quiz_score = c(88, NA, 12),
post_quiz_score = c(NA, NA, 90))
I want to implement this in a "tidyverse" way and vectorized to get something like
----------------------------------------------------------------------------
| ls | pre_quiz_score | post_quiz_score |
| 425 L0=40/42 | 88 | NA |
| NA | NA | NA |
| 789 L8=5/6 | 12 | 90 |
So far, I haven't gotten stringr::str_split
, gsub
, or sub
to work correctly, mostly because I end up removing just the |
's or all the string but the last |
and after.
I hope that makes sense, thanks!
Just implement the logic as you stated it: