I am giving you two solutions here. The first one uses base R and the second one uses the tidyverse. There is one third solution with data.table
; however, I am not proficient with the package. It is nevertheless an extremely powerful package when you learn how to use it.
Base R solution
data <- data.frame(x1 = 1:10,
x2 = c("A", "X","X","X","X", "A", "A", "B","A", "B"),
x3 = c(" ", "B", "A", "F","F", " "," ", " "," "," "),
x4 = factor(c("B", "B", "A", "F", "A", "B", "A", "B","A", "B")),
stringsAsFactors = FALSE)
data[data$x2 == "X", "x2"] <- data[data$x2 == "X", "x3"]
data
x1 x2 x3 x4
1 1 A B
2 2 B B B
3 3 A A A
4 4 F F F
5 5 F F A
6 6 A B
7 7 A A
8 8 B B
9 9 A A
10 10 B B
Tidyverse solution
library(dplyr)
data <- data.frame(x1 = 1:10,
x2 = c("A", "X","X","X","X", "A", "A", "B","A", "B"),
x3 = c(" ", "B", "A", "F","F", " "," ", " "," "," "),
x4 = factor(c("B", "B", "A", "F", "A", "B", "A", "B","A", "B")),
stringsAsFactors = FALSE)
data %>%
mutate(x2 = ifelse(x2 == "X", x3, x2))
x1 x2 x3 x4
1 1 A B
2 2 B B B
3 3 A A A
4 4 F F F
5 5 F F A
6 6 A B
7 7 A A
8 8 B B
9 9 A A
10 10 B B