-1

I have a df:

df1 <- data.frame(rbind(c('C001','begin', ''), 
c('C001','contac', 'yes'), 
c('C001','motivation', 'no'), 
c('C001','other', ''), 
c('C002','begin', ''), 
c('C002','contac', 'yes'), 
c('C002','motivation', 'yes'), 
c('C002','other', 'big'), 
c('C003','begin', ''), 
c('C003','contac', 'no'), 
c('C003','request', 'no'), 
c('C003','other', '')))

I need to attribute the value of column X1 to column X3 when in X2 I have ‘begin’, to get something like this:

df2 <- data.frame(rbind(c('C001','begin', 'C001'), 
c('C001','contac', 'yes'), 
c('C001','motivation', 'no'), 
c('C001','other', ''),
c('C002','begin', 'C002'), 
c('C002','contac', 'yes'), 
c('C002','motivation', 'yes'), 
c('C002','other', 'big'), 
c('C003','begin', 'C003'), 
c('C003','contac', 'no'), 
c('C003','request', 'no'), 
c('C003','other', '')))

How can I do this? I still work only with base-r.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • Maybe this helps: https://stackoverflow.com/questions/47164902/using-r-to-mutate-columns-based-on-the-value-of-another-column – RobertoT Jun 02 '22 at 10:04

1 Answers1

0

Using dplyr:

library(dplyr)
df1 %>%
  mutate_if(is.factor, as.character) %>%
  mutate(X3 = if_else(X2 == "begin", X1, X3 ))
VvdL
  • 2,799
  • 1
  • 3
  • 14