[R] Superscript and for loops
David Winsemius
dwinsemius at comcast.net
Wed Apr 3 19:44:16 CEST 2013
On Apr 3, 2013, at 9:06 AM, Shane Carey wrote:
> Hi,
>
> If I have data as follows:
> DATA_names<-c(
> "A mg kg"
> "B mg kg"
> "C mg kg"
> "D mg kg"
> "E mg kg"
> "F mg kg"
> "G mg kg"
> "H mg kg"
>
> How do I convert to:
> -1
> A (mg kg )
> -1
> B (mg kg )
> -1
> C (mg kg )
> -1
> D (mg kg )
> -1
> E (mg kg )
> -1
> F (mg kg )
> -1
> G (mg kg )
> -1
> H (mg kg )
>
> I have lots of elements and I need to do this automatically in a for loop
> or the like?
You haven't described the task in very much detail, so Bill Dunlap's language-oriented (more "expressive" as it were) solution my be what you really need. Nonetheless, this answer stays on the character-plane of R's conceptual levels:
gsub("mg kg", "(mg kg)^-1", DATA_names)
[1] "A (mg kg)^-1" "B (mg kg)^-1" "C (mg kg)^-1" "D (mg kg)^-1" "E (mg kg)^-1" "F (mg kg)^-1"
[7] "G (mg kg)^-1" "H (mg kg)^-1"
If you wanted these in an expression vector suitable for labels on a barplot or such:
sapply(gsub("mg kg", "(mg kg)^-1", DATA_names), as.expression)
expression(`A (mg kg)^-1` = "A (mg kg)^-1", `B (mg kg)^-1` = "B (mg kg)^-1",
`C (mg kg)^-1` = "C (mg kg)^-1", `D (mg kg)^-1` = "D (mg kg)^-1",
`E (mg kg)^-1` = "E (mg kg)^-1", `F (mg kg)^-1` = "F (mg kg)^-1",
`G (mg kg)^-1` = "G (mg kg)^-1", `H (mg kg)^-1` = "H (mg kg)^-1")
In practice:
> pos <- barplot(1:length(DATA_names))
> text(x=pos,y=-1, xpd=TRUE, srt=45,
labels= sapply( gsub("mg kg", "(mg kg)^-1", DATA_names),
as.expression))
--
David Winsemius
Alameda, CA, USA
More information about the R-help
mailing list