2

I have two vectors "data1" and "data2". I want to create a list of these two vectors. But when I create a list of these two vectors I want the names of the variables in the list to be "$data1" and "$data2" instead of [[1]] and [[2]]. Below is the code for better understanding:

data1 <- c(3,4,5,6,7)  
data2 <- c(8,9,10,11)  
datalist <- list(data1,data2)

The output is:

datalist
# [[1]]
# [1] 3 4 5 6 7

# [[2]]
# [1]  8  9 10 11

Instead I want this to be the output without actually setting the names myself. Is there any way the names of the variables in the list get set automatically.

datalist
# $data1
# [1] 3 4 5 6 7

# $data2
# [1]  8  9 10 11
G_1991
  • 139
  • 11
  • I don't want to set the names myself. Is there anyway during the creation of the list that the names of the parameters to the list() function become the names of the variables. – G_1991 May 11 '15 at 10:50
  • Do you want the names to be these specific values or do you want them derived from whatever the original source data values were? – John May 11 '15 at 11:07
  • Yes, I want it to be derived from whatever the original source data values are . – G_1991 May 11 '15 at 11:10

3 Answers3

5

You can try

 datalist <- mget(paste0('data',1:2))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Try

names(datalist) <- c("data1", "data2")

Or to make it more dynamic

names(datalist) <- paste0('data',1:2)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

You could also use setNames:

datalist <- setNames(list(data1, data2), c("data1", "data2"))
Karsten W.
  • 17,826
  • 11
  • 69
  • 103
  • My initial thought was `setNames`, but based on OP's comments, I guess `setNames` is not an option – akrun May 11 '15 at 11:25