[R] sapply() with cat()
Gabor Grothendieck
ggrothendieck at myway.com
Thu Sep 16 07:52:45 CEST 2004
Prof Brian Ripley <ripley <at> stats.ox.ac.uk> writes:
:
: On Thu, 16 Sep 2004, Kevin Wang wrote:
:
: > 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.
:
: cat writes to connection (here stdout) and then returns NULL. I think you
: meant to use paste():
:
: goo <- function(x)ifelse(x > 3.8, paste("\\textbf{", x, "}", sep = ""), x)
:
: works.
:
Also, if you convert your data frame to a matrix you won't need sapply:
inter.mat <- as.matrix(inter.df)
ifelse(inter.mat > 3.8,
paste("\\textbf{", inter.mat, "}", sep = ""),
inter.mat)
More information about the R-help
mailing list