Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 85

Add and Delete Elements of a List

Оглавление

A numbered element can be added while skipping positions. In the following example the position 3 is left undefined (NULL).

L <- list(1,2) L[4] <- 4 # position 3 is NULL L ## [[1]] ## [1] 1 ## ## [[2]] ## [1] 2 ## ## [[3]] ## NULL ## ## [[4]] ## [1] 4

Named elements are always added at the end of the list:

L$pi_value <- pi L ## [[1]] ## [1] 1 ## ## [[2]] ## [1] 2 ## ## [[3]] ## NULL ## ## [[4]] ## [1] 4 ## ## $pi_value ## [1] 3.141593

Delete an element by assigning NULL to it:

L[1] <- NULL L ## [[1]] ## [1] 2 ## ## [[2]] ## NULL ## ## [[3]] ## [1] 4 ## ## $pi_value ## [1] 3.141593

It is also possible to delete an element via the squared brackets. Note that if we address the elements of a list by their number, we need to recalculate the numbers. If we were addressing the elements of the list by name, nothing needs to be changed.

L <- L[-2] L ## [[1]] ## [1] 2 ## ## [[2]] ## [1] 4 ## ## $pi_value ## [1] 3.141593

The Big R-Book

Подняться наверх