简体   繁体   中英

Replacing values in data frame column based on another column

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.

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)

Using data.table

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

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)
  )

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM