0

My data looks like:

x             y  
2             5
3             6
4             2
6             1
7             10
12            16
145           1

Looking to output the number that's smaller than the other into a new column which would look like:

x             y           z
2             5           2
3             6           3
4             2           2
6             1           1
7             10          7
12            16          12
145           1           1

None of the data will be equal so you don't need to worry about that.

x <- c(2,3,4,6,7,12,145)
y <- c(5,6,2,1,10,16,1)
df <- data.frame(x,y)

2 Answers2

1

Using case_when from tidyverse

remove(list = ls())
x <- c(2,3,4,6,7,12,145)
y <- c(5,6,2,1,10,16,1)
df <- data.frame(x,y)


df <- df %>%
    mutate(z = 
        case_when(
            x < y ~ x,
            TRUE ~ y
        )
    )
df
Henry Cyranka
  • 2,970
  • 1
  • 16
  • 21
1

You can use pmin to get minimum between x and y columns.

df$z <- pmin(df$x, df$y)
df
#    x  y  z
#1   2  5  2
#2   3  6  3
#3   4  2  2
#4   6  1  1
#5   7 10  7
#6  12 16 12
#7 145  1  1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213