[R] Split Strings

William Michels wjm1 at caa.columbia.edu
Mon Jan 18 00:50:36 CET 2016


> str_1 <- list("pc_m2_45_ssp3_wheat", "pc_m2_45_ssp3_wheat", "ssp3_maize", "m2_wheat")
> str_2 <- strsplit(unlist(str_1), "_")
> max.length <- max(sapply(str_2,length))
> str_3 <- lapply(lapply(str_2, unlist), "length<-", max.length)
> str_3

See: http://stackoverflow.com/questions/27995639/i-have-a-numeric-list-where-id-like-to-add-0-or-na-to-extend-the-length-of-the

Hope this helps,

Bill

William Michels, Ph.D.


On Sun, Jan 17, 2016 at 12:56 PM, Miluji Sb <milujisb at gmail.com> wrote:
> I have a list of strings of different lengths and would like to split each
> string by underscore "_"
>
> pc_m2_45_ssp3_wheat
> pc_m2_45_ssp3_wheat
> ssp3_maize
> m2_wheat
>
> I would like to separate each part of the string into different columns
> such as
>
> pc m2 45 ssp3 wheat
>
> But because of the different lengths - I would like NA in the columns for
> the variables have fewer parts such as
>
> NA NA NA m2 wheat
>
> I have tried unlist(strsplit(x, "_")) to split, it works for one variable
> but not for the list - gives me "non-character argument" error. I would
> highly appreciate any help. Thank you!
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list