1

I would like an efficient way to replace values of many columns to NAif they are bigger than the value of a different column.

For example: replace all values in columns height1:height5 with NA if these values are >height6

set.seed(1)

# example data
N <- 200
data <- data.frame(id = 1:N,
               height1 = rnorm(N,50:60),
               height2 = rnorm(N,60:70),
               height3 = rnorm(N,70:80),
               height4 = rnorm(N,80:90),
               height5 = rnorm(N,90:100),
               height6 = rnorm(N,60:110))
2
  • 1
    Your question is unclear. If Row 1 looks like [1,55,65,75,85,95,90] Then height5 is greater than height6, so do you want to replace all values in height5 with NA, or just the value on that row? And do you want to replace all values in the row with NA (like height1, height2, ..., height5) with NA? Please be more specific by giving an example, if needed. Commented Dec 11, 2018 at 15:55
  • I would like to replace just the value for the row for the specific column that are greater than height6. I.e for row 1 the value of height5 would be NA Commented Dec 11, 2018 at 15:58

1 Answer 1

4

Using dplyr you can do

data %>% mutate_at(
   vars(height1:height5),
   ~ifelse(.x > data$height6, NA, .x)
   )
Sign up to request clarification or add additional context in comments.

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.