Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how can I build a list with some elements referring to earlier elements in the list?

I'm trying to do something like this:

opts = list(
  width=128,
  overlap=width/2,
)

But, as expected, I get

Error: object 'width' not found

What is a good idiom for salvaging this code snippet?

like image 949
Metamorphic Avatar asked Jan 09 '20 06:01

Metamorphic


People also ask

How do you reference an element in a list in R?

In order to reference a list member directly, we have to use the double square bracket "[[]]" operator. The following object x[[2]] is the second member of x. In other words, x[[2]] is a copy of s, but is not a slice containing s or its copy.

How do I create a list of elements in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.

How do you subset a list in R?

To subset lists we can utilize the single bracket [ ] , double brackets [[ ]] , and dollar sign $ operators. Each approach provides a specific purpose and can be combined in different ways to achieve the following subsetting objectives: Subset list and preserve output as a list. Subset list and simplify output.

How do I append a list to a list in R?

To add or append an element to the list in R use append() function. This function takes 3 parameters input list, the string or list you wanted to append, and position. The list. append() function from the rlist package can also use to append one list with another in R.


2 Answers

You can use dplyr::lst which is same as list but here you can build the components sequentially.

dplyr::lst(
  width = 128, 
  overlap=width/2,
)

#$width
#[1] 128

#$overlap
#[1] 64
like image 156
Ronak Shah Avatar answered Sep 18 '22 23:09

Ronak Shah


Another option is:

opts = list(
  width={width<-128},
  overlap=width/2
)
like image 29
chinsoon12 Avatar answered Sep 20 '22 23:09

chinsoon12