[R] sapply() with cat()

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Sep 16 07:37:50 CEST 2004


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.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list