1

I have a data frame in R :

 a  b  c     d   e
 1  2  3    23   1
 4  5  6  -Inf   2
 7  8  9     2   8
10 11 12  -Inf NaN

and I'd like to replace all the values in column e with NA if the corresponding value in column d is -Inf like this:

 a  b  c     d   e
 1  2  3    23   1
 4  5  6  -Inf  NA
 7  8  9     2   8
10 11 12  -Inf  NA

Any help is appreciated. I haven't been able to do it without loops, and its taking a long time for the full data frame.

3 Answers 3

3

ifelse is vectorize. We can use ifelse without using a loop.

dat$e <- ifelse(dat$d == -Inf, NA, dat$e)

DATA

dat <- read.table(text = "a  b  c     d   e
 1  2  3    23   1
 4  5  6  -Inf   2
 7  8  9     2   8
10 11 12  -Inf NaN", header = TRUE)
Sign up to request clarification or add additional context in comments.

Comments

2

Using data.table

library(data.table)
setDT(dat)[is.infinite(d), e := NA]

Comments

2

A solution with dplyr:

library(tidyverse)
df <- tribble(
~a,  ~b,  ~c, ~d, ~e,
1, 2, 3, 23, 1, 
4, 5, 6, -Inf, 2, 
7, 8, 9, 2, 8, 
10, 11, 12, -Inf, NaN)

df1 <- df %>% 
  dplyr::mutate(e = case_when(d == -Inf ~ NA_real_,
                              TRUE ~ e)
  )

enter image description here

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.