user2821029
user2821029

Reputation: 153

create r vector with names

I have this output that I can create with static inputs:

t1 = c("dog"="dog","cat"= "cat")
t1

Results:
     dog   cat 
    "dog" "cat" 

How can I create those same results with only the t$animal character vector below

t = data.frame(animal = c("dog","cat"))
c(t$animal =t$animal)  # this does not work

Upvotes: 0

Views: 69

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269461

Convert to character and then use names<- (or setNames):

ch <- as.character(unlist(t))
names(ch) <- ch
ch
##   dog   cat 
## "dog" "cat" 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388817

You can use setNames

t2 <- setNames(t$animal, t$animal)
t2

#dog cat 
#dog cat 

data

t <- data.frame(animal = c("dog","cat"))

Upvotes: 0

Related Questions