Wednesday, June 24, 2009

Delete a List Component in R

In R, the way to delete a component in a list object is different from matrix and vector objects.

For a vector, to delete an element:

vec <- c(1, 2, 3)
vec <- vec[-3]

For a matrix, to delete a row or a column:

mat <- matrix(c(1,2,3,4), 2, 2)
mat2 <- mat[-1,] # delete a row
mat3 <- mat[,-1] # delete a column

For a list, to delete a component:

lis <- vector("list", 3)
lis[[3]] <- NULL

Just assign a NULL value to a component, it will delete such a component in the list.

No comments: