[R] Concatenate a Variable
Marc Schwartz
marc_schwartz at comcast.net
Fri Feb 1 15:36:59 CET 2008
Carla Rebelo wrote:
> Good morning!
>
> I do not speak English very well and so I will try to explain the best I
> can. I have this:
>
> > tabela[,1]
> [1] a a b b a c b a c c c c c
> Levels: a b c
>
> >unique(tabela[,1])
> [1] a b c
> Levels: a b c
>
> >var<-unique(tabela[,1])[1]
>
> > var
> [1] a
> Levels: a b c
>
> But if I concatenate like this
> > cat("VAR: ", var, "\n")
>
> I obtain
> >VAR: 1
>
> and I want to obtain
> >VAR: a
>
> How can I do this? Thanks!
'a' is a factor, thus you are getting the underlying numeric code as the
output.
Note from ?cat:
Currently only atomic vectors (and so not lists) and names are handled.
Character strings are output ‘as is’ (unlike print.default which escapes
non-printable characters and backslash — use encodeString if you want to
output encoded strings using cat). Other types of R object should be
converted (e.g. by as.character or format) before being passed to cat.
Thus:
var <- factor("a", levels = c("a", "b", "c"))
> var
[1] a
Levels: a b c
> is.vector(var)
[1] FALSE
So 'var' is not an atomic vector and you must therefore coerce it to a
character vector using as.character() before passing it to cat():
> cat("VAR: ", as.character(var), "\n")
VAR: a
HTH,
Marc Schwartz
More information about the R-help
mailing list