I need to split a string in a dataframe at the last "space" before character 25
I built this function that works for plain text variables, but does not work in mutate.
What am I missing??
# Example
# HLF 11/7/17
# Goal: Split text string at last space before char 24
#
suppressWarnings(library(tidyverse))
#> Loading tidyverse: ggplot2
#> Loading tidyverse: tibble
#> Loading tidyverse: tidyr
#> Loading tidyverse: readr
#> Loading tidyverse: purrr
#> Loading tidyverse: dplyr
#> Conflicts with tidy packages ----------------------------------------------
#> filter(): dplyr, stats
#> lag(): dplyr, stats
suppressWarnings(library(stringr))
suppressWarnings(library(reprex))
splitdesc <- function(t){
t1 <- str_sub(t, 1, 25)
x1 <- str_locate_all(t1, " ") # get positions of all spaces
x1df <- as.data.frame(x1) # convert to data frame to find nrow
r1 <- nrow(x1df) # get position of last row
s1 <- x1df[r1,1] # get value from last row
desc1 <- str_trim(str_sub(t, 1, s1))
return(desc1)
}
#
test1 <- c("now is the time for all good men to come...")
splitdesc(test1) # this works
#> [1] "now is the time for all"
#
test2 <- tibble(CODE = c("a", "b"), DESC = c("apple peaches pumpkin pie for Thanksgiving",
"the quick brown fox jumped over the lazy dog") )
test3 <- mutate(test2, DESC3 = splitdesc(DESC)) # this does mot work
#> Error in mutate_impl(.data, dots): Evaluation error: arguments imply differing number of rows: 3, 4.