w3resource

Create a List in R with Vectors, Matrices, and Functions

R Programming: Basic Exercise-19 with Solution

Write a R program to create a list of elements using vectors, matrices and a functions. Print the content of the list.

Sample Solution :

R Programming Code :

# Create a list with various elements:
# - A numeric vector
# - The built-in vector of month abbreviations
# - A 2x2 matrix with specified values
# - The 'asin' function
l = list(
  c(1, 2, 2, 5, 7, 12),  # Numeric vector
  month.abb,              # Vector of month abbreviations
  matrix(c(3, -8, 1, -3), nrow = 2),  # 2x2 matrix
  asin                    # 'asin' function
)

# Print a message indicating the content of the list
print("Content of the list:")

# Print the content of the list
print(l)

Output:

[1] "Content of the list:"
[[1]]
[1]  1  2  2  5  7 12

[[2]]
 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"

[[3]]
     [,1] [,2]
[1,]    3    1
[2,]   -8   -3

[[4]]
function (x)  .Primitive("asin")                         

Explanation:

  • Create a List:
    • l = list(...) initializes a new list l with several elements.
  • First Element:
    • c(1, 2, 2, 5, 7, 12) is a numeric vector.
  • Second Element:
    • month.abb is a built-in vector containing abbreviated month names ("Jan", "Feb", etc.).
  • Third Element:
    • matrix(c(3, -8, 1, -3), nrow = 2) creates a 2x2 matrix with the specified values.
  • Fourth Element:
    • asin is the built-in R function for computing the arcsine.
  • Print List Content:
    • print("Content of the list:") prints a label for the list.
    • print(l) displays the contents of the list l.

R Programming Code Editor:



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

Previous: Write a R program to create an array with three columns, three rows, and two "tables", taking two vectors as input to the array. Print the array.
Next: Write a R program to draw an empty plot and an empty plot specify the axes limits of the graphic.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/basic/r-programming-basic-exercise-19.php