Advertisement

R语言abs函数计算数值数据对象的绝对值实战

阅读量:

R Programming absolute value function for numerical data object calculation practical guide

目录

R语言abs函数计算数值数据对象的绝对值实战

#基本语法

#计算向量对象的绝对值

计算矩阵对象的绝对值

计算dataframe的绝对值

计算dataframe特定列的绝对值

两个数值的绝对差


#基本语法

R语言绝对值计算的基本语法

abs(x)

#计算向量对象的绝对值

复制代码
 x <- c(- 5, 9, 3, - 1, 2)                 # Create example vector

    
 # -5  9  3 -1  2
    
 x_abs <- abs(x)                           # Apply abs function in R
    
 x_abs                                     # Print output to RStudio console
    
 # 5 9 3 1 2

# 计算矩阵对象的绝对值

复制代码
 mat <- matrix(- 9:5, nrow = 3, ncol = 5)  # Create example matrix

    
 mat                                       # Print output to RStudio console
    
  
    
  
    
 mat_abs <- abs(mat)                       # Apply abs function to matrix
    
 mat_abs                                   # Print output to RStudio console

# 计算dataframe的绝对值

复制代码
 df <- as.data.frame(mat)                  # Convert matrix to data.frame

    
 df                                        # Print output to RStudio console
    
  
    
 df_abs <- abs(df)                         # Apply abs function to matrix                           
    
 df_abs                                    # Print output to RStudio console

# 计算dataframe特定列的绝对值

复制代码
 df_col_abs <- df                          # Duplicate example data.frame

    
  
    
 df_col_abs$V2 <- abs(df_col_abs$V2)       # Absolute value only of one column
    
 df_col_abs                                # Print output to RStudio console

# 两个数值的绝对差

复制代码
 diff <- 5 - 20                            # Difference of two values

    
 diff                                      # Print output to RStudio console
    
 # -15
    
  
    
 diff_abs <- abs(diff)                     # Calculate absolute difference
    
 diff_abs                                  # Print output to RStudio console
    
 # 15

参考:R abs Function (6 Example Codes) | How to Calculate an Absolute Value

参考:statisticsglobe.com

参考:R

全部评论 (0)

还没有任何评论哟~