[R] Split values in vector
Gerrit Eichner
Gerrit.Eichner at math.uni-giessen.de
Thu Jan 19 13:42:24 CET 2012
Hi, Johannes,
maybe
X <- unlist( strsplit( as.character( x$ART), split = ";", fixed = TRUE))
X <- strsplit( X, split = "-", fixed = TRUE)
X <- sapply( X, function( x)
if( length(x) == 2)
rep( x[1], as.numeric( x[2])) else x[1]
)
table(X, useNA = "always")
comes close to what you want.
Hth -- Gerrit
On Thu, 19 Jan 2012, Johannes Radinger wrote:
> Hello,
>
> I have a vector which looks like
>
> x$ART
> ...
> [35415] 00 01-1;02-1;05-1;
> [35417] 01-1; 01-1;02-1;
> [35419] 01-1; 00
> [35421] 01-1;04-1; 05-1;
> [35423] 02-1; 01-1;02-1;
> [35425] 01-1;02-1; <NA>
> [35427] 01-1; <NA>
> ...
>
>
> This is a vector I got in this format. To explain it:
> there are several categories (00,01,02 etc) and its counts (values after -)
> So I have to split each value and create new dataframe-columns/vectors
> for each categories one column and the value should be then in the
> corresponding cell. I know that this vector has 7 categories (00-06)
> and NA values but each case (row) has not all the categories (as you can see). How can do such as split?
>
> In the end I should get:
> x$ART_00, x$ART_01, x$ART_03,... with its values. In the case of <NA> all the categories should have also <NA>.
>
> Maybe someone can help.
>
> Thank you,
>
> Best regards
>
> Johannes
>
>
>
> --
> "Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ...
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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