Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R list() Function - Creating a List

R list() Function - Creating a List

R Language Examples R Language Examples

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

)

print

(

"Student information list:"

)

print

(

student

)

Access list elements via $ or [[ ]]

print

(

paste

(

"Name:"

, student$name

)

)

print

(

paste

(

"Age:"

, student$age

)

)

print

(

paste

(

"Scores:"

,

toString

(

student$scores

)

)

)

print

(

paste

(

"First subject:"

, student$scores

[

1

]

)

)

Access nested elements

print

(

paste

(

"List length:"

,

length

(

student

)

)

)

print

(

"List names:"

)

print

(

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 R Language Examples