[R] Split string

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Apr 15 10:18:57 CEST 2009


try this:

string <- c("0.30", "0.55", "0.45", "2.30", "NA", "  NA", "  NA", 
"0.50", "0.30", "0.30", "0.45", "0.30")

splt <- strsplit(string, "\\.")
sapply(splt, function (x) if(length(x) == 2) x[1] else as.character(NA))
sapply(splt, function (x) if(length(x) == 2) x[2] else as.character(NA))


I hope it helps.

Best,
Dimitris


Peter Kraglund Jacobsen wrote:
>> (FICB[,"temp"])
>  [1] "0.30" "0.55" "0.45" "2.30" "0.45" "0.30" "0.25" "0.30" "0.30"
> "1.05" "1.00" "1.00"
> [13] "0.30" "0.30" "0.30" "0.55" "0.30" "0.30" "0.30" "0.25" "1.00"
> "0.30" "0.30" "0.45"
> [25] "0.30" "1.30" "0.30" "0.30" "0.45" "0.30" "0.30" "0.30" "  NA"
> "NA" "  NA" "  NA"
> [37] "0.30" "  NA" "0.30" "0.30" "0.30" "0.30" "  NA" "  NA" "0.35"
> "NA" "0.35" "0.30"
> [49] "0.30" "0.40" "  NA" "0.40" "0.30" "  NA" "0.30" "0.30" "0.30"
> "0.30" "0.45" "0.30"
> [61] "0.30" "0.30" "0.30" "0.50" "0.30" "0.30" "0.45" "0.30"
> 
> How do I output the number to the left of "." to variable X and the
> two numbers to the right of "." to variable Y?
> 
> FICB[,"x"] <- substr(FICB[,"temp2"],1,1)
> Works, but
> 
> FICB[,"y"] <- substr(FICB[,"temp2"],3,2)
> only returns "". temp is class character.
> 
> ______________________________________________
> 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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list