0

I want to recode NA and NaN values for rows where a column value is X. Here is my data structure.

V1  V2  V3   V4  V5  
1   4   9    15  A 
2   12  12   3   B
3  NaN  7    NA  X

I want to replace NaN and NA values to 999 where V5 = X

V1  V2  V3   V4  V5  
1   4   9    15  A 
2   12  12   3   B
3  999  7   999  X

I used the code below, but it is not working

df2 <- replace_na(df$V5 == "X", 999)

Can someone help?

D. Fowler
  • 443
  • 2
  • 5
  • 1
    I think this is a pure R programming question which you should post in stackoverflow, or at least check there for existing solutions – StupidWolf Jul 29 '20 at 21:14
  • ```df[df$V5 == "X"),c("V1","V2","V3","V4")] = "X"``` should work, but if you have a factor for V1,V2,V3,V4, it will fail – StupidWolf Jul 29 '20 at 21:16

1 Answers1

0

You can use e.g. replace() from base R for this:

# which rows
df_which <- which(df$V5 == "X")

# replace NAs with 999
df[df_which, ] <- replace(df[df_which, ], is.na(df[df_which, ]), 999)

df
#>   V1  V2 V3  V4 V5
#> 1  1   4  9  15  A
#> 2  2  12 12   3  B
#> 3  3 999  7 999  X

Created on 2020-07-29 by the reprex package (v0.3.0)

Data

df <- structure(list(V1 = 1:3, V2 = c(4, 12, NaN), V3 = c(9L, 12L, 
7L), V4 = c(15L, 3L, NA), V5 = c("A", "B", "X")), class = "data.frame", row.names = c(NA, 
-3L))
  • Thank you, Petr. I am getting the following message when I use that code: "Error in df[df_which, ] : object of type 'closure' is not subsettable." Any ideas about why I might be getting that? – D. Fowler Jul 29 '20 at 21:28
  • @D.Fowler Is `df` in your case the correct data frame? Use the real name of your data frame... or try to run `class(df)` and let me know. –  Jul 29 '20 at 21:33
  • 1
    Ahh, what a silly mistake on my end. You were correct, I forgot to change the df name. Thank you, Petr. Much appreciated! – D. Fowler Jul 29 '20 at 21:40
  • There are NaN values that I also want to code as 999. I tried this: "rest_sleep_3[df_which, ] – D. Fowler Jul 29 '20 at 22:01
  • @D.Fowler It should work with my solution as well - try in your R console `is.na(NaN) == TRUE` - and `is.nan()` also should work. Are these NaN values really NaN values or is it only a string "NaN" or something like that? –  Jul 30 '20 at 04:51