Can you name a variable without declaring it?

Viewed 55

When I'm using functions that output tables, I like to see some variable names. However, I'm a very lazy man who doesn't want to write three lines when I write one. Take a simple function like tail. What I like to do is:

boxes<-1:50
names(boxes)<-paste("Box",boxes)
tail(boxes)

and this will get me the output:

Box 45 Box 46 Box 47 Box 48 Box 49 Box 50 
    45     46     47     48     49     50 

However, that felt like too much work to me. The bulk of my code was spent naming boxes. What I wanted to write was something like

tail((1:50);names(1:50)<-paste("Box",1:50))

Is anything like this possible for when I want to name a variable without declaring it?

1 Answers

We could use setNames without creating an object

setNames(1:50, paste0("Box", 1:50))

Or another option is enframe/deframe

library(tibble)
deframe(enframe(sprintf("Box%d", 1:50))[2:1])         
Related