在 R 中查找向量元素的乘积
在本文中,我们将看到如何在 R 编程语言中找到向量元素的乘积。
方法一:使用迭代
方法
- 创建数据框
- 遍历向量
- 在我们进行时乘以元素
- 展示产品
下面的代码片段说明了 for 循环在小数点向量上的应用。得到的乘积也是十进制的。
例子:
R
# declaring a floating point vector
vec <- c(1.1,2,3.2,4)
size = length(vec)
# initializing product as 1
prod = 1
# looping over the vector elements
for(i in 1:size)
{
# multiplying the vector element at ith index
# with the product till now
prod = vec[i]*prod
}
print("Product of vector elements:")
# in-built application of prod function
print(prod)
R
# declaring a floating point vector
vec <- c(1.1,2,NA,11,4)
size = length(vec)
# initializing product as 1
prod = 1
# looping over the vector elements
for(i in 1:size)
{
# multiplying the vector element at
# ith index with the product till now
prod = vec[i]*prod
cat("Product after iteration:")
print(prod)
}
print("Final product of vector elements:")
# in-built application of prod function
print(prod)
R
# declaring a integer vector
vec <- c(1,2,3,4)
print("Product of vector elements:")
# in-built application of prod function
print(prod(vec))
输出
[1] “Product of vector elements:”
[1] 28.16
另一个示例演示了对缺失值(即 NA 值)的任何数学运算的行为。在这种情况下,返回的产品是 NA。
示例 2:
电阻
# declaring a floating point vector
vec <- c(1.1,2,NA,11,4)
size = length(vec)
# initializing product as 1
prod = 1
# looping over the vector elements
for(i in 1:size)
{
# multiplying the vector element at
# ith index with the product till now
prod = vec[i]*prod
cat("Product after iteration:")
print(prod)
}
print("Final product of vector elements:")
# in-built application of prod function
print(prod)
输出
Product after iteration:[1] 1.1
Product after iteration:[1] 2.2
Product after iteration:[1] NA
Product after iteration:[1] NA
Product after iteration:[1] NA
[1] “Final product of vector elements:”
[1] NA
方法 2:使用 prod()
R 中的 prod()函数是一种内置方法,可以直接计算向量中指定为其参数的各个元素的乘积。如果存在单个参数,它会计算向量的各个元素的乘法输出。
句法:
prod(vector)
例子:
电阻
# declaring a integer vector
vec <- c(1,2,3,4)
print("Product of vector elements:")
# in-built application of prod function
print(prod(vec))
输出
[1] “Product of vector elements:”
[1] 24