[R] extract data from square cracket
Marc Girondot
marc_grt at yahoo.fr
Thu May 17 07:12:03 CEST 2012
Le 17/05/12 03:37, Min Wang a écrit :
> Dear Sir or Madam,
>
> I have a question like this. I want to extract the following data from the
> square bracket:
>
> 1 band band [0.86]
> 2 band band [0.93]
> 3 noband noband [0.95]
> 4 noband noband [0.91]
> 5 noband noband [0.89]
> 6 noband noband [0.84]
> 7 noband noband [0.89]
> 8 band noband [0.80]
> 9 band band [0.75]
> 10 band band [0.93]
>
> For the 4th column, I want to get the numerical values inside the bracket.
> How can I use R code to implement this? Thanks.
>
>
Many possibilities. For exemple:
> a <- '[0.84]'
> gsub("[^[:digit:].]", "", a)
[1] "0.84"
Look at
?gsub
To reproduce your specific example:
d <- data.frame(col1=c(rep("band", 2), rep("noband", 5), rep("band", 3)))
d<- data.frame(cbind(d, col2=c(rep("band", 2), rep("noband", 6),
rep("band", 2))))
d<- data.frame(cbind(d, col3=c("[0.86]", "[0.93]", "[0.95]", "[0.91]",
"[0.89]", "[0.84]", "[0.89]", "[0.80]", "[0.75]", "[0.93]")))
as.numeric(gsub("[^[:digit:].]", "", d[,"col3"]))
Then you get:
[1] 0.86 0.93 0.95 0.91 0.89 0.84 0.89 0.80 0.75 0.93
Sincerely,
Marc
--
__________________________________________________________
Marc Girondot, Pr
Laboratoire Ecologie, Systématique et Evolution
Equipe de Conservation des Populations et des Communautés
CNRS, AgroParisTech et Université Paris-Sud 11 , UMR 8079
Bâtiment 362
91405 Orsay Cedex, France
Tel: 33 1 (0)1.69.15.72.30 Fax: 33 1 (0)1.69.15.73.53
e-mail: marc.girondot at u-psud.fr
Web: http://www.ese.u-psud.fr/epc/conservation/Marc.html
Skype: girondot
More information about the R-help
mailing list