Create a List in R with Vectors, Matrices, and Functions
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.
Go to:
PREV : 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.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?