Georgery
Georgery

Reputation: 8117

Change Vector Type keep Names

Sorry, if this is a duplicate. I could not find an answer.

I have a named vector (logical in this case):

a <- c("a" = TRUE, "b" = TRUE, "c" = FALSE, "e" = FALSE)

a
a     b     c     e 
TRUE  TRUE FALSE FALSE 

If I turn it into an integer, the names are gone.

> as.integer(a)
[1] 1 1 0 0

How can I prevent this?

Upvotes: 2

Views: 117

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101941

You can use the following code

a <- +a

such that

> a
a b c e 
1 1 0 0 

Upvotes: 1

s_baldur
s_baldur

Reputation: 33508

Some alternatives

class(a) <- "integer"
a b c e 
1 1 0 0 

Or

ifelse(a, 1L, 0L)
a b c e 
1 1 0 0 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389065

You can preserve the attributes of a by using []

a[] <- as.integer(a)
#a b c e 
#1 1 0 0

Upvotes: 4

Related Questions