How to replace X in one column by values of another column in R

In this dataframe, I would like to replace "X" values in x2 by x1 or x3 or x4

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)

Hi @Khoajak ,

What you are trying to do is fairly simple; however we need more information in order to be able to help you. What condition needs to be met in order to know if the "X" in column x2 must be replaced by the value is x1, x3 or x4?

Hi gueyenono,
Thank you very much for your help. I just want to replace "X" values in column x2 by values of the same rows of column x3 of the data frame. Thank you again.

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
1 Like

Thank you very much. It helped.

I'm glad to hear. You should consider marking my answer as the solution so that potential future readers will also be helped by it.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.