JoshDG
JoshDG

Reputation: 3931

Converting numeric type vector into a vector of strings

I'm trying to convert this:

> j[1:5] 
NA06985 NA06991 NA06993 NA06994 NA07000

Into this:

c("NA06985","NA06991","NA06993", "NA06994", "NA07000")

I've tried using as.character but it gives me:

> as.character(j[1:5])
[1] "10" "10" "10" "10" "10"

Help please! -Josh

EDIT: Okay so I think I figured it out. After doing class(j) I found that it was of type data.frame. So I converted to as.matrix and it worked..hooray!

Upvotes: 12

Views: 27521

Answers (3)

verbamour
verbamour

Reputation: 995

paste(j[1:5])

This works for strings, factors, numerics, pretty much anything that can be displayed.

Upvotes: 11

JoshDG
JoshDG

Reputation: 3931

Okay so I think I figured it out. After doing class(j) I found that it was of type data.frame. So I converted to as.matrix and it worked..hooray!

Upvotes: 1

Thierry
Thierry

Reputation: 18487

Assumming that j is a factor

> j <- factor(c("NA06985","NA06991","NA06993", "NA06994", "NA07000", "extra level"))
> j
[1] NA06985     NA06991     NA06993     NA06994     NA07000     extra level
Levels: extra level NA06985 NA06991 NA06993 NA06994 NA07000
> levels(j)[j[1:5]]
[1] "NA06985" "NA06991" "NA06993" "NA06994" "NA07000"

Upvotes: 0

Related Questions