How to add a key / value pair of a variable to a list of objects?

I have two variables, key and value , and I want to add them as a key / value pair to the list:

 key = "width" value = 32 mylist = list() mylist$key = value 

The result is the following:

 mylist # $key # [1] 32 

But I would like this instead:

 mylist # $width # [1] 32 

How can i do this?

+44
list r
Jul 09 '09 at 18:20
source share
4 answers

R-lists can be considered as hash vectors of objects that can be accessed by name. Using this approach, you can add a new entry to the list as follows:

 key <- "width" value <- 32 mylist <- list() mylist[[ key ]] <- value 

Here we use the string stored in the variable key to access the position in the list, similar to using the value stored in the loop variable i to access the vector through:

 vector[ i ] 

Result:

 myList $width [1] 32 
+57
Jul 09 '09 at 19:33
source share

List items in R can be called. So in your case itโ€™s just

  > mylist = list() > mylist$width = value 

When R meets this code

 > l$somename=something 

where l is the list. He adds something to the list and calls it with the name somename. You can access it using

 > l[["somename"]] 

or

 > l$somename 

The name can be changed with the command names:

 > names(l)[names(l)=="somename"] <- "othername" 

Or, if now the position of the item in the list:

 > names(l)[1] <- "someothername" 
+13
Jul 24 '09 at 8:06
source share

The built-in setNames() function makes it easy to create a hash from given lists of keys and values. (Thanks to Nick K for the best offer.)

Usage: hh <- setNames(as.list(values), keys)

Example:

 players <- c("bob", "tom", "tim", "tony", "tiny", "hubert", "herbert") rankings <- c(0.2027, 0.2187, 0.0378, 0.3334, 0.0161, 0.0555, 0.1357) league <- setNames(as.list(rankings), players) 

Then accessing the values โ€‹โ€‹through the keys is easy:

 league$bob [1] 0.2027 league$hubert [1] 0.0555 
+7
Jul 08 '15 at 16:53
source share

We can use the data structure of list R to store data in the form of a key-value pair.

Syntax:

ObjectName<-list("key"= value)

Example:

mylist<-list("width"=32)

also see example: "https://github.com/WinVector/zmPDSwR/blob/master/Statlog/GCDSteps.R"

0
Oct 21 '17 at 19:48 on
source share



All Articles