[英]replacing text with NA in R
I have a variable PC_R
in dataframe jd_df
that describes laboratory test results. 我在数据帧jd_df
中有一个变量PC_R
,用于描述实验室测试结果。 I'd like to replace some of the data in this variable (eg tf, QNS, rej) with NA. 我想用NA替换此变量中的某些数据(例如tf,QNS,rej)。 I've tried this code: 我已经试过这段代码:
jd_df %>%
replace(PC_R,TF,NA)
and this: 和这个:
jd_df %>%
replace(jd_df,PC_R==TF,NA)
and this: 和这个:
jd_df %>%
replace(PC_R,"TF","NA")
and this: 和这个:
jd_df %>%
replace(jd_df,PC_R%in%TF,NA)
I keep getting the error: 我不断收到错误:
Error in replace(., jd_df, PC_R %in% TF, NA) : unused argument (NA)
I'm wondering if the replace command is not the way to go. 我想知道替换命令是否不可行。
You can achieve this using case_when as demonstrated using the iris dataset below 您可以使用case_when实现此目的,如下面的虹膜数据集所示
library(dplyr)
iris <- iris %>%
mutate(Species = as.character(Species)) %>%
mutate(Species = case_when(
Species == "setosa" ~ NA_character_,
TRUE ~ Species
))
Multiple changes can be specified as such: 可以这样指定多个更改:
iris %>%
mutate(Species = as.character(Species)) %>%
mutate(Species = case_when(
Species == "setosa" | Species == "versicolor" ~ NA_character_,
TRUE ~ Species
))
Created on 2019-02-16 by the reprex package (v0.2.0). 由reprex软件包 (v0.2.0)创建于2019-02-16。
我发现这可以将多个字符文本更改为NA:
jd_df %>% mutate(PC_R = replace(PC_R, PC_R %in% "TF"|PC_R %in% "tf"|PC_R %in% "rej",NA))
The case_when()
answer above works well! 上面的case_when()
答案很好! A simpler alternative is the na_if()
function, which replaces a specified string with NA
. 一个更简单的替代方法是na_if()
函数,该函数将指定的字符串替换为NA
。 As such: 因此:
library(dplyr)
iris %>%
mutate(Species = na_if(Species, "setosa"))
This will change all instances of setosa
to NA
in the column Species
. 这将改变所有实例setosa
到NA
列Species
。 In your case, it could be: 在您的情况下,可能是:
jd_df %>%
mutate(PC_R = na_if(PC_R, "TF"))
Which replaces all "TF"
with NA
. 用NA
替换所有"TF"
。 You can repeat the code as needed to catch all your intended NA
values: 您可以根据需要重复代码以捕获所有预期的NA
值:
jd_df %>%
mutate(PC_R = na_if(PC_R, "TF"),
PC_R = na_if(PC_R, "QNS"),
PC_R = na_if(PC_R, "rej"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.