R list() Function - Creating a List
The R list() function is used to create a list, which is the most flexible data structure in R.
A list can contain elements of different types and lengths, making it ideal for organizing complex data.
The syntax of the list() function is as follows:
list(...)
Example
Create a list containing multiple types
student
<-
list
(
name
=
"Zhang San"
,
age
=
25
,
scores
=
c
(
88
,
92
,
76
)
,
passed
=
TRUE
)
(
"Student information list:"
)
(
student
)
Access list elements via $ or [[ ]]
(
paste
(
"Name:"
, student$name
)
)
(
paste
(
"Age:"
, student$age
)
)
(
paste
(
"Scores:"
,
toString
(
student$scores
)
)
)
(
paste
(
"First subject:"
, student$scores
[
1
]
)
)
Access nested elements
(
paste
(
"List length:"
,
length
(
student
)
)
)
(
"List names:"
)
(
names
(
student
)
)
The output of the code above is:
[1] "学生信息列表:"
$name
[1] "张三"
$age
[1] 25
$scores
[1] 88 92 76
$passed
[1] TRUE
[1] "姓名: 张三"
[1] "年龄: 25"
[1] "第一科: 88"
[1] "列表长度: 4"
[1] "列表名称:"
[1] "name" "age" "scores" "passed"
R Language Examples