0
votes

I would like to refer to another value in the same tibble and mutate my initial value into that. For example if I have a tibble,

tibble(x = 200:203, y = c("a","b","c", "d"), z = c(NA, 202,201,NA))

I would like to get tibble(x = 200:203, y = c("a","b","c", "d"), z = c(NA, "c","b",NA))

as a result.

I have tried mutate(tbl,z, ifelse(!is.na(z), tbl[[which(fixed_messages$id == z),2]], NA)) but it doesn't work.

Also how do I insert a tibble into a stackoverflow question?

2
The best way to insert a tibble into a StackOverflow question is using dput(...), see stackoverflow.com/questions/5963269/…Bas

2 Answers

0
votes

We can left_jointhe tibble with itself and select columns that we need.

library(dplyr)

left_join(df, df, by = c('x' = 'z')) %>% select(x, y = y.x, z = y.y)

# A tibble: 4 x 3
#     x   y     z    
#  <dbl> <chr> <chr>
#1   200 a     NA   
#2   201 b     c    
#3   202 c     b    
#4   203 d     NA   
0
votes

You can do:

tbl %>%
 mutate(z = y[match(z, x)])

      x y     z    
  <int> <chr> <chr>
1   200 a     <NA> 
2   201 b     c    
3   202 c     b    
4   203 d     <NA>