-4

I have a data frame that looks like this

 A      B      C
one    NULL   one
NULL   one    NULL
NULL   one    one

How to efficiency replace the Null with 0 and the "one" with 1? Please NOTE that I am not asking for how to replace NULL with 0, I am asking how to replace NULL with 0 AND "one" with 1 in an efficient way

owise
  • 1,055
  • 16
  • 28
  • 1
    is it'" `NULL`" (text/string) or an R `NULL` value? There are similar q's on SO. Which ones did you try and found confusing? This is also not a code-writing service. That did you try that did not work? – hrbrmstr Nov 08 '17 at 15:25
  • 1
    This is a simple recoding question that can be found via a quick search. If you've tried that and your problem is for some reason it doesn't work for your application you can explain show us what you tried and how it fails. Basically: `df[df$var=="oldvalue"] <- newvalue` – cparmstrong Nov 08 '17 at 15:27
  • 2
    Possible duplicate of [Replacing NULL values in a data.frame](https://stackoverflow.com/questions/46133499/replacing-null-values-in-a-data-frame) – nghauran Nov 08 '17 at 15:34
  • I said "efficiency "!! Not ´df[df$var=="oldvalue"] <- newvalue`. In this way I need to go through every single column and manually do it!! –  owise Nov 08 '17 at 15:35

2 Answers2

1

You can use replace() from dplyr:

library(dplyr)


df %>% # replace df with your dataframe
  replace(. == "NULL", 0) %>%
  replace(. == "one", 1)

  A B C
1 1 0 1
2 0 1 0
3 0 1 1
clemens
  • 6,653
  • 2
  • 19
  • 31
0

mapvalues from plyr with the help of supply did the job

df_new=  tbl_df(sapply(df, function(x)  mapvalues(x, c("NULL", "1"), c(0,1))  ))
owise
  • 1,055
  • 16
  • 28