Ask Your Question
3

How can I add additional columns to a matrix that consists of lists?

asked 2022-01-23 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-01-17 04:00:00 +0000

woof gravatar image

You can add additional columns to a matrix that consists of lists in several ways. Here are two examples:

  1. Using cbind() function: Suppose that you have a matrix "my_matrix" consisting of two lists "list1" and "list2" as below:
my_matrix <- matrix(list(list1=c(1,2,3), list2=c("a","b","c")), nrow=3)

To add an additional column to "my_matrix" consisting of a new list "list3", you can use the cbind() function as follows:

new_list <- list("d", "e", "f")
my_matrix <- cbind(my_matrix, new_list)

This will add the new list "newlist" as a new column to the matrix "mymatrix".

  1. Using matrix indexing: Suppose that you have a matrix "my_matrix" consisting of two lists "list1" and "list2" as below:
my_matrix <- matrix(list(list1=c(1,2,3), list2=c("a","b","c")), nrow=3)

To add an additional column to "my_matrix" consisting of a new list "list3", you can use matrix indexing as follows:

new_list <- list("d", "e", "f")
my_matrix <- cbind(my_matrix, list())
my_matrix[,3] <- new_list

This will add a new, empty column to "mymatrix" using cbind() function first, and then populate the column with the new list "newlist" using matrix indexing.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-23 11:00:00 +0000

Seen: 13 times

Last updated: Jan 17 '22