简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM