R语言 获取和设置矢量的长度 – length() 函数。需要更改标题

R语言 获取和设置矢量的长度 – length() 函数。需要更改标题

R编程语言 中的length()函数 用于获取或设置向量(列表)或其他对象的长度。

R语言 获取对象的长度

在这里,我们将在R编程中获得向量的长度,为此我们将使用length()函数。

语法: length(x)

参数

  • x: 向量或对象

例1:获取向量的长度

# R program to illustrate
# length function
 
# Specifying some vectors
x <- c(6)
y <- c(1, 2, 3, 4, 5)
 
# Calling length() function
# to get length of the vectors
length(x)
length(y)
R

输出:

[1] 1
[1] 5
R

例2:获取矩阵的长度

A = matrix(
      
  # Taking sequence of elements
  c(1, 2, 3, 4, 5, 6, 7, 8, 9),
    
  # No of rows
  nrow = 3, 
    
  # No of columns
  ncol = 3,       
    
  # By default matrices are in column-wise order
  # So this parameter decides how to arrange the matrix
  byrow = TRUE        
)
print(A)
 
# length of A
length(A)
R

输出

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

9
R

例3:获取数据框的长度

这里的BOD数据框有6行2列,给出了水质评价中生化需氧量与时间的关系。我们要得到这个数据框的长度。

print(BOD)
 
length(BOD)
R

输出

  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

2
R

注意: 如果参数是一个矩阵或数据框架,则返回变量的数量。

例4:获取列表的长度

# R program to create a List and get the len
 
# The first attributes is a numeric vector
# containing the employee IDs which is created
# using the command here
empId = c(1, 2, 3, 4)
 
# The second attribute is the employee name
# which is created using this line of code here
# which is the character vector
empName = c("Debi", "Sandeep", "Subham", "Shiba")
 
# The third attribute is the number of employees
# which is a single numeric variable.
numberOfEmp = 4
 
# We can combine all these three different
# data types into a list
# containing the details of employees
# which can be done using a list command
empList = list(empId, empName, numberOfEmp)
 
print(empList)
 
print("Length of the list:")
length(empList)
R

输出

[[1]]
[1] 1 2 3 4

[[2]]
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

[[3]]
[1] 4

[1] "Length of the list:"

3
R

例5:获取字符串的长度

在R语言中,我们不能轻易获得字符串的长度,首先,我们必须使用split来获得字符串的字符,然后解列每个字符来计算长度。

# R program to split a string
 
# Given String
string <- "Geeks For Geeks"
 
# Basic application of length()
length(string)  
 
# unlist the string and then count the length
length(unlist(strsplit(string, "")))
R

输出

1
15
R

R语言 设置对象的长度

这里我们将在R编程中设置向量的长度,为此我们将使用length()函数。

语法: length(x) <- value

参数

  • x: 向量或对象
# R program to illustrate
# length function
 
# Specifying some vectors
x <- c(3)
y <- c(1, 2, 3, 4, 5)
z <- c(1, 2, 3, 4, 5)
 
# Setting length of the vector
length(x) <- 2
length(y) <- 7
length(z) <- 3
 
# Getting elements of the
# new vectors
x
y
z
R

输出

[1]  3 NA
[1]  1  2  3  4  5 NA NA
[1] 1 2 3
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册