Kundera
Kundera

Reputation: 15

How to create new columns based on other columns' values using R

I have a dataframe (df) in r, and I am interested in two columns, df$LEFT and df$RIGHT. I would like to create two new columns such that in df$BEST I have the smaller number between LEFT and RIGHT for each row. Analogously, I want to create the column df$WORST where it is stored the smallest number.

ID LEFT RIGHT
1  20   70
2  65   15
3  25   65

I would like to obtain this:

ID LEFT RIGHT BEST WORST
1  20   70    20   70
2  65   15    15   65
3  25   65    25   65

How can I do that?

Upvotes: 1

Views: 35

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61214

An alternative is using apply

> df$WORST <- apply(df[,-1], 1, min)
> df$BEST <- apply(df[,-1], 1, max)
> df
  ID LEFT RIGHT WORST BEST
1  1   20    70    20   70
2  2   65    15    15   65
3  3   25    65    25   65

Using @akrun's approach with transform:

> transform(df,
            WORST =  apply(df[,-1], 1, min),
            BEST = apply(df[,-1], 1, max))

Upvotes: 1

akrun
akrun

Reputation: 887831

We can use pmin/pmax to get the corresponding minimum, maximum values of the two columns

transform(df, BEST = pmin(LEFT, RIGHT), WORST = pmax(LEFT, RIGHT))
#  ID LEFT RIGHT BEST WORST
#1  1   20    70   20    70
#2  2   65    15   15    65
#3  3   25    65   25    65

data

df <- structure(list(ID = 1:3, LEFT = c(20L, 65L, 25L), RIGHT = c(70L, 
  15L, 65L)), class = "data.frame", row.names = c(NA, -3L))

Upvotes: 1

Related Questions