Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change negative values in dataframe column to absolute value

Tags:

dataframe

r

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?

like image 660
Cybernetic Avatar asked Mar 10 '14 16:03

Cybernetic


People also ask

How do you take the absolute value of a column in a data frame?

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.

How do I replace negative numbers in R?

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).


3 Answers

abs(dat)

where dat is the name of your data frame.

like image 51
Sven Hohenstein Avatar answered Oct 11 '22 09:10

Sven Hohenstein


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
like image 40
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 11 '22 09:10

A5C1D2H2I1M1N2O1R2T1


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.

like image 2
Workhorse Avatar answered Oct 11 '22 11:10

Workhorse