Reputation: 23
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
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
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