How can operations be performed in arrays in R language?

In R language, you can perform operations on elements in an array using vectorized operations. This means directly operating on the entire vector or array without needing to use loops to process each element individually. Here are some common vectorized operation functions:

  1. Addition, subtraction, multiplication, division:
# 创建一个数组
arr <- c(1, 2, 3, 4, 5)

# 数组中的每个元素加上1
arr_plus_one <- arr + 1

# 数组中的每个元素减去2
arr_minus_two <- arr - 2

# 数组中的每个元素乘以3
arr_times_three <- arr * 3

# 数组中的每个元素除以4
arr_divide_four <- arr / 4
  1. Operations such as squaring, square roots, and exponential calculations.
# 数组中的每个元素求平方
arr_square <- arr^2

# 数组中的每个元素开方
arr_sqrt <- sqrt(arr)

# 数组中的每个元素求e的指数
arr_exp <- exp(arr)
  1. Statistical functions such as sum, average, maximum, and minimum values, etc.
# 数组中的所有元素求和
arr_sum <- sum(arr)

# 数组中的所有元素平均值
arr_mean <- mean(arr)

# 数组中的所有元素最大值
arr_max <- max(arr)

# 数组中的所有元素最小值
arr_min <- min(arr)

With these vectorized operation functions, it is convenient to perform various mathematical calculations and statistical operations on the elements in the array.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds