R语言 查找矢量元素的乘积
在这篇文章中,我们将看到如何在R编程语言中找到矢量元素的乘积。
方法1:使用迭代
方法
- 创建数据框架
- 遍历矢量
- 边走边乘以元素
- 显示积
下面的代码片段显示了对小数点向量的for循环的应用。得到的乘积也是小数类型的。
例子
# 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)
输出
[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