0
$\begingroup$

I am new to R and would like some assistance on replacing multiple values in a large dataset with many variables to NA at once in r.

I want all the cells with "<0.01, <0.02, and many others with < sign at the beginning" to be changed to NA. Data screenshot

How do I do it at once? Here is a screenshot of the data.

$\endgroup$
0
$\begingroup$

Using gsub with a regular expression to replace every string starting with a "<" with NA.

x <- c("<0.01", "0.027", "<0.01", "<0.01", "0.2", "0.22", "0.04", "0.09")
gsub("<.*", NA, x)
# [1] NA      "0.027" NA      NA      "0.2"   "0.22"  "0.04"  "0.09" 
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you @Oxbowerce, I tried your suggestion but nothing changed. They still have the < sign. $\endgroup$ – Ndahambelela Sep 17 at 12:14
  • $\begingroup$ Could you export a sample of your dataframe using dput(head(x, 5)) where x is the name of your dataframe and paste it here? $\endgroup$ – Oxbowerce Sep 17 at 13:32
  • $\begingroup$ structure(list(Date = c("43887", "43885"), Year = c(2020, 2020 ), Month = c(2, 2), Day = c(26, 24), pH = c("8.3000000000000007", "8.1"), Colour = c("17", "<1"), Conductivity = c("48.9", "55.9" ), SO4 = c("34", "56"), NO3 = c("1.1000000000000001", "1.2"), NO2 = c("<0.1", "<0.1"), Fe = c("0.04", "0.02"), Mn = c("0.01", "<0.01"), Cu = c("<0.01", "<0.01"), Zn = c("<0.01", "0.01" ), Cd = c("<0.01", "<0.01")), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame")) $\endgroup$ – Ndahambelela Sep 17 at 15:32
  • $\begingroup$ How are you executing the code? Using gsub("<.*", NA, x$Colour) works perfectly fine for me, returning "17" NA for "17", "<1". $\endgroup$ – Oxbowerce Sep 17 at 17:24
  • $\begingroup$ I see now, I was not specifying the column name. Thank you very much, I will do it like that from now on (each column separately). $\endgroup$ – Ndahambelela Sep 17 at 17:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.