Sidharth Bhatia
Sidharth Bhatia

Reputation: 23

Checking 2 columns for equality, if equal make a new col

If

data$col1==data$col2 

Then

data$newcol==data$col1

Elseif

data$col3==data$col2

Then

data$newcol==data$col2

I want rows not to loose their identity

Upvotes: 0

Views: 127

Answers (2)

antom
antom

Reputation: 11

You can try this approach using dplyr::mutate()

library(dplyr) # 0.7.4

set.seed(10)

dtf <- data_frame(
    col1 = sample(1:20, 10),
    col2 = sample(1:20, 10),
    col3 = sample(1:20, 10)
)


dtf %>%
    mutate(new_col = case_when(
               col1 == col2 ~ col1,
               col3 == col2 ~ col2,
               TRUE ~ NA_integer_
           ))

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

A column has to have some value for every row, even if you don't want to define it. I think you can try using ifelse here:

data$newcol = ifelse(data$col1 == data$col2, data$col1, NA)

In the event that a given row has col1 not equal to col2, NA would be assigned to the new column.

Upvotes: 1

Related Questions