R list() Function - Create a List

R 语言实例R Language Examples

The R list() function is used to create lists, which are the most flexible data structure in R.

Lists can contain elements of different types and lengths, making them ideal for organizing complex data.

The syntax of the list() function is as follows:

list(...)

Examples

# 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(Score:, 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 executing the above code 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 语言实例R Language Examples

Other Extensions