0

I have a data frame like below:

 field1  field2  field3
   x     1      2
   y     3      4
   x     na     na

My goal is to replace all the values in field2 to A and field3 to B when field1 ='x'. I wrote two lines to do this and want to see if there is a way to do this in one line.

df$field2[df$field1=='x'] <- 'A'

df$field3[df$field1=='x'] <- 'B'

Thanks!

3 Answers 3

1

base

df <- data.frame(field1 = c("x", "y", "x"),
                 field2 = c(1, 3, NA),
                 field3 = c(2, 4, NA))

df[df$field1 == "x", c("field2", "field3")] <- list("A", "B")

data.table

library(data.table)
dt <- data.table(field1 = c("x", "y", "x"),
                 field2 = c(1, 3, NA_character_),
                 field3 = c(2, 4, NA_character_))

dt[field1 == "x", `:=`(field2 = "A", field3 = "B")]
Sign up to request clarification or add additional context in comments.

Comments

1

Using dplyr:

df %>% 
  mutate(field2 = case_when(field1 == "x" ~ "A", 
                            TRUE ~ field2),
         field3 = case_when(field1 == "x" ~ "B", 
                            TRUE ~ field3))

Not one line, but clean.

Comments

0

You may use a matrix for replacement.

df1[df1$field1 == "x", 2:3] <- t(matrix(c("A", "B"), 2, 2))
df1
#   field1 field2 field3
# 1      x      A      B
# 2      y      3      4
# 3      x      A      B

Data

df1 <- structure(list(field1 = c("x", "y", "x"), field2 = c("A", "3", 
"A"), field3 = c("B", "4", "B")), row.names = c(NA, -3L), class = "data.frame")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.