Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

R Programming: Create a list containing a vector, a matrix and a list and give names to the elements in the list

R Programming: List Exercise-3 with Solution

Write a R program to create a list containing a vector, a matrix and a list and give names to the elements in the list. Access the first and second element of the list.

Sample Solution :

R Programming Code :

list_data <- list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11), nrow = 2),
list("Python", "PHP", "Java"))
print("List:")
print(list_data)
names(list_data) = c("Color", "Odd numbers", "Language(s)")
print("List with column names:")
print(list_data)
print('1st element:')
print(list_data[1])
print('2nd element:')
print(list_data[2])

Sample Output:

[1] "List:"
[[1]]
[1] "Red"   "Green" "Black"

[[2]]
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    3    7   11

[[3]]
[[3]][[1]]
[1] "Python"

[[3]][[2]]
[1] "PHP"

[[3]][[3]]
[1] "Java"


[1] "List with column names:"
$Color
[1] "Red"   "Green" "Black"

$`Odd numbers`
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    3    7   11

$`Language(s)`
$`Language(s)`[[1]]
[1] "Python"

$`Language(s)`[[2]]
[1] "PHP"

$`Language(s)`[[3]]
[1] "Java"


[1] "1st element:"
$Color
[1] "Red"   "Green" "Black"

[1] "2nd element:"
$`Odd numbers`
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    3    7   11                         

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to list containing a vector, a matrix and a list and give names to the elements in the list.
Next: Write a R program to create a list containing a vector, a matrix and a list and add element at the end of the list.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?