0
votes

I'm looking for an easy way to add the minimum value for each column inside my dataframe.

This feels like a common thing, but I haven't been able to find any good answers yet...maybe I'm missing something obvious.

Let's say I've got two columns (in reality I have close to 100) with positive and negative numbers.

w <- c(9, 9, 9, 9)
x <- c(-2, 0, 1, 3)
y <- c(-1, 1, 3, 4)

z <- as.data.frame(cbind(w, x, y))

  w  x  y
1 9 -2 -1
2 9  0  1
3 9  1  3
4 9  3  4

I want z to look like this after a transformation for only x and y columns [,2:3]

  w  x  y
1 9  0  0
2 9  2  2
3 9  3  4
4 9  5  5

Does that make sense?

3

3 Answers

1
votes
library(dplyr)

dplyr::mutate(z, across(c(x, y), ~ . + abs(min(.))))

  w x y
1 9 0 0
2 9 2 2
3 9 3 4
4 9 5 5

You can also do by column position rather than column name by changing c(x,y) to 2:3 or c(2:3, 5) for non-sequential column positions.

1
votes

Depends exactly what you mean and what you want to happen if there aren't negative values. No matter the values, this will anchor the minimum at 0, but you should be able to adapt it if you want something slightly different.

z[] = lapply(z, function(col) col - min(col))
z
#   x y
# 1 0 0
# 2 2 2
# 3 3 4
# 4 5 5

As a side note, as.data.frame(cbind(x, y)) is bad - if you have a mix of numeric and character values, cbind() will convert everything to character. It's shorter and better to simplify to data.frame(x, y).

0
votes

Do you want

z[] <- lapply(z, function(columnValues) columnValues + abs(min(columnValues)))