I have a data.frame like this:
    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
How can I change the negative values to their absolute values?
The abs() function is used to get a Series/DataFrame with absolute numeric value of each element. This function only applies to elements that are all numeric. Returns: Series/DataFrame containing the absolute value of each element.
Data Visualization using R Programming To convert negative values in a matrix to 0, we can use pmax function. For example, if we have a matrix called M that contains some negative and some positive and zero values then the negative values in M can be converted to 0 by using the command pmax(M,0).
abs(dat)
where dat is the name of your data frame.
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
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With