R 基于另一列替换数据框列中的值
我在R中有一个数据帧:R 基于另一列替换数据框列中的值,r,dataframe,R,Dataframe,我在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 如果d列中的对应值是-Inf,我想用NA替换e列中的所有值 像这样: 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 感谢您的帮助。如果没有
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
如果d列中的对应值是-Inf,我想用NA替换e列中的所有值
像这样:
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
感谢您的帮助。如果没有循环,我无法完成这项工作,而且整个数据帧需要很长时间。
如果else
是矢量化的。我们可以使用ifelse
而不使用循环
dat$e <- ifelse(dat$d == -Inf, NA, dat$e)
dat$eifelse
是矢量化的。我们可以使用ifelse
而不使用循环
dat$e <- ifelse(dat$d == -Inf, NA, dat$e)
dat$e使用data.table
library(data.table)
setDT(dat)[is.infinite(d), e := NA]
使用数据表
library(data.table)
setDT(dat)[is.infinite(d), e := NA]
使用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)
)
库(tidyverse)
df带有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)
)
库(tidyverse)
df