[R] Split Strings

Adrian Dușa dusa.adrian at unibuc.ro
Sun Jan 17 22:17:15 CET 2016


Try this:

mylist <- list("pc_m2_45_ssp3_wheat", "pc_m2_45_ssp3_wheat", "ssp3_maize",
"m2_wheat")
mylist <- lapply(mylist, function(x) unlist(strsplit(x, split="_")))
allstrings <- unique(unlist(mylist))
lapply(mylist, function(x) allstrings[match(allstrings, x)])

[[1]]
[1] "pc"    "m2"    "45"    "ssp3"  "wheat" NA

[[2]]
[1] "pc"    "m2"    "45"    "ssp3"  "wheat" NA

[[3]]
[1] NA   NA   NA   "pc" NA   "m2"

[[4]]
[1] NA   "pc" NA   NA   "m2" NA

Hope this helps,
Adrian

On Sun, Jan 17, 2016 at 10: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.
>



-- 
Adrian Dusa
University of Bucharest
Romanian Social Data Archive
Soseaua Panduri nr.90
050663 Bucharest sector 5
Romania

	[[alternative HTML version deleted]]



More information about the R-help mailing list