📌  相关文章
📜  计算 R 中列表元素的数量

📅  最后修改于: 2022-05-13 01:55:33.183000             🧑  作者: Mango

计算 R 中列表元素的数量

在本文中,我们将使用 R 编程语言计算列表中的元素和嵌套列表中的元素。因此,我们将使用length()lengths()来查找列表中的元素计数。

脚步 -

  • 使用向量/列表/范围运算符创建列表
  • 使用长度和长度函数查找元素的数量。

让我们使用范围、向量和列表创建一个列表。



R
# range from 10 to 50
values = 10:50
  
# vector elements of character type
names = c("sravan", "bobby", "ojaswi", "gnanu")
  
# data1 with list of elements
data1 = list(1, 2, 3, 4, 5)
  
# give input to the data which is a list
data = list(values, names, data1)
  
# display
print(data)


R
# range from 10 to 50
values = 10:50
  
# vector elements of character type
names = c("sravan", "bobby", "ojaswi", "gnanu")
  
# data1 with list of elements
data1 = list(1, 2, 3, 4, 5)
  
# give input to the data which is a list
data = list(values, names, data1)
  
# display
print(data)
  
# count elements using length function
print(length(data))


R
# range from 10 to 50
values = 10:50
  
# vector elements of character type
names = c("sravan", "bobby", "ojaswi", "gnanu")
  
# data1 with list of elements
data1 = list(1, 2, 3, 4, 5)
  
# give input to the data which is a list
data = list(a1 = values, a2 = names, a3 = data1)
  
# display
print(data)
  
# count elements in each nested  using lengths function
print(lengths(data))


R
# data1 with list of elements
data1 = list(1, 2, 3, 4, 5)
  
# data2 with list of elements
data2 = list("a", 'b', 'c')
  
# give input to the data which is a list
data = list(a1 = data1, a2 = data2)
  
# display
print(data)
  
# count elements in each nested  using length function
print(length(data))
print("-----")
  
# count elements in each nested  using lengths function
print(lengths(data))


输出:

示例 1:使用 length()函数。

长度函数用于统计列表中的元素

下面是实现:



电阻

# range from 10 to 50
values = 10:50
  
# vector elements of character type
names = c("sravan", "bobby", "ojaswi", "gnanu")
  
# data1 with list of elements
data1 = list(1, 2, 3, 4, 5)
  
# give input to the data which is a list
data = list(values, names, data1)
  
# display
print(data)
  
# count elements using length function
print(length(data))

输出:

示例 2:为了查找列表(嵌套列表)中每个数据的长度,我们将使用 lengths()函数

下面是实现:

电阻

# range from 10 to 50
values = 10:50
  
# vector elements of character type
names = c("sravan", "bobby", "ojaswi", "gnanu")
  
# data1 with list of elements
data1 = list(1, 2, 3, 4, 5)
  
# give input to the data which is a list
data = list(a1 = values, a2 = names, a3 = data1)
  
# display
print(data)
  
# count elements in each nested  using lengths function
print(lengths(data))

输出:

示例 3: R 程序对嵌套列表中的元素进行计数

电阻

# data1 with list of elements
data1 = list(1, 2, 3, 4, 5)
  
# data2 with list of elements
data2 = list("a", 'b', 'c')
  
# give input to the data which is a list
data = list(a1 = data1, a2 = data2)
  
# display
print(data)
  
# count elements in each nested  using length function
print(length(data))
print("-----")
  
# count elements in each nested  using lengths function
print(lengths(data))

输出: