Change negative values in dataframe column to absolute value

If you have a dataframe that consists of a mix of both numeric and character columns:

#dataframe is your original dataframe. 

abs.dat <- data.frame %>% 
  dplyr::select(where(is.numeric)) %>%
  abs()

Only select numeric columns.


You can just do something like the following (assuming your original data.frame is called "mydf"):

mydf[] <- lapply(mydf, abs)
mydf
#   Col1 Col2 Col3 Col4 Col5  Col6
# 1 1982    0    0  211  107     0
# 2 4412    0  989    0  296     0
# 3    0 5051    0  267  389   920
# 4    0 2983    0  215    0  1639
# 5    0 1326    0  861    0     0
# 6 3722    0   89    0  243 13349

abs(dat)

where dat is the name of your data frame.

Tags:

R

Dataframe