[R] sapply() with cat()
Kevin Wang
Kevin.Wang at maths.anu.edu.au
Thu Sep 16 07:16:38 CEST 2004
Hi,
Suppose I've got a data frame:
> inter.df
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
1 3.3 NA NA NA NA NA NA NA NA NA NA NA
2 0.0 0.1 NA NA NA NA NA NA NA NA NA NA
3 1.0 0.9 0.2 NA NA NA NA NA NA NA NA NA
4 1.6 0.0 2.9 0.7 NA NA NA NA NA NA NA NA
5 0.0 0.1 2.9 0.1 0.1 NA NA NA NA NA NA NA
6 2.4 1.0 0.6 0.4 1.9 0.1 NA NA NA NA NA NA
7 2.8 1.4 1.2 7.5 0.0 0.0 4.2 NA NA NA NA NA
8 0.3 3.1 0.8 3.7 5.7 0.0 0.8 0.0 NA NA NA NA
9 0.1 2.9 0.3 1.3 0.2 0.2 0.5 1.4 0.9 NA NA NA
10 0.8 2.6 0.0 0.0 0.1 4.1 0.8 4.3 0.6 2.2 NA NA
11 0.0 4.0 0.0 0.3 0.5 0.9 0.0 1.5 0.2 0.7 0.8 NA
12 0.6 0.8 0.3 0.0 0.2 1.2 0.0 0.8 1.5 0.9 0.4 0
>
> foo <- function(x) {
+ ifelse(x > 3.8, NA, x)
+ }
> sapply(inter.df, foo)
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
[1,] 3.3 NA NA NA NA NA NA NA NA NA NA NA
[2,] 0.0 0.1 NA NA NA NA NA NA NA NA NA NA
[3,] 1.0 0.9 0.2 NA NA NA NA NA NA NA NA NA
[4,] 1.6 0.0 2.9 0.7 NA NA NA NA NA NA NA NA
[5,] 0.0 0.1 2.9 0.1 0.1 NA NA NA NA NA NA NA
[6,] 2.4 1.0 0.6 0.4 1.9 0.1 NA NA NA NA NA NA
[7,] 2.8 1.4 1.2 NA 0.0 0.0 NA NA NA NA NA NA
[8,] 0.3 3.1 0.8 3.7 NA 0.0 0.8 0.0 NA NA NA NA
[9,] 0.1 2.9 0.3 1.3 0.2 0.2 0.5 1.4 0.9 NA NA NA
[10,] 0.8 2.6 0.0 0.0 0.1 NA 0.8 NA 0.6 2.2 NA NA
[11,] 0.0 NA 0.0 0.3 0.5 0.9 0.0 1.5 0.2 0.7 0.8 NA
[12,] 0.6 0.8 0.3 0.0 0.2 1.2 0.0 0.8 1.5 0.9 0.4 0
Up to here, sapply() does what I want, replacing values that are greater
than 3.8 to NA, as per my foo() function. But...
> goo <- function(x) {
+ ifelse(x > 3.8, cat("\\textbf{", x, "}", sep = ""), x)
+ }
> sapply(inter.df, goo)
\textbf{NA0.10.900.111.43.12.92.640.8}Error in "[<-"(`*tmp*`, test,
value = rep(yes, length.out = length(ans))[test]) :
incompatible types
If instead whenever I get a value that's greater than 3.8 I want to
change it what goo() does, e.g. the value 4.0 should become:
\textbf{4.0}
but I got the above error.
What I'm intending is to then pass the inter.df (with the \textbf{}
markups) into xtable() so the values will be bolded in the resulting
LaTeX table (as so far, I cannot see how I can achieve bolding only
certain numbers with xtable() alone).
Any suggestions will be welcome!
Kevin
--
Ko-Kang Kevin Wang
PhD Student
Centre for Mathematics and its Applications
Building 27, Room 1004
Mathematical Sciences Institute (MSI)
Australian National University
Canberra, ACT 0200
Australia
Homepage: http://wwwmaths.anu.edu.au/~wangk/
Ph (W): +61-2-6125-2431
Ph (H): +61-2-6125-7407
Ph (M): +61-40-451-8301
More information about the R-help
mailing list