r - using stringr to split vectors, unexpected result length -
something simple i'm messing in using stringr
manipulate character vectors. have data frame of following sort
library(stringr) d1 <- data.frame(x = str_c(rpois(10, lambda=5), rpois(10, lambda=10), sep = "_"))
and want after underscore separate variable. use of str_sub
results in vector of length 20, , i'm @ loss explain why.
d1$y <- str_sub(d1$x, str_locate(d1$x, fixed("_"))+1)
error in
$<-.data.frame
(*tmp*
, "y", value = c("_12", "_7", "_15", : replacement has 20 rows, data has 10
could direct me how write str_sub
call in right way?
this want doing (check out output of str_locate
see why wasn't working you, note str_sub
recycles arguments):
d1$y = str_sub(d1$x, str_locate(d1$x, fixed("_"))[,1] + 1, -1)
or in base r:
d1$y = sub("^[^_]*_", "", d1$x)
Comments
Post a Comment