0

I have a large data frame which has more than 500 rows and 40 columns like;

dataframe <- data.frame(ID=c("ID1","ID2","ID3","..."), column1=c(1,NA,0,1), column2=c(1,0,0,1),column3=c(1,NA,NA,NA),... = c (1,0,1,1))

Now in column 3, there are three 'NA' values, and I want to replace column3 of ID2 to numerical value '1'.

Please tell me the good way to do so.

tantan
  • 57
  • 5
  • Does this answer your question? [How do I replace NA values with zeros in an R dataframe?](https://stackoverflow.com/questions/8161836/how-do-i-replace-na-values-with-zeros-in-an-r-dataframe) – Travis Jan 11 '20 at 01:44

2 Answers2

1

You can subset the specific cell and then assign the value

dataframe$column3[dataframe$ID == "ID2" & is.na(dataframe$column3)] <- 1

We can also use replace

transform(dataframe, column3 = replace(column3, ID == "ID2" & is.na(column3), 1))

 #   ID column1 column2 column3
 #1 ID1       1       1       1
 #2 ID2      NA       0       1
 #3 ID3       0       0      NA
 #4 ID4       1       1      NA

data

dataframe <- data.frame(ID=c("ID1","ID2","ID3", "ID4"), 
              column1=c(1,NA,0,1), column2=c(1,0,0,1),column3=c(1,NA,NA,NA))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can use data.table methods

library(data.table)
setDT(dataframe)[ID == "ID2" & is.na(column3), column3 := 1] 
dataframe
#    ID column1 column2 column3
#1: ID1       1       1       1
#2: ID2      NA       0       1
#3: ID3       0       0      NA
#4: ID4       1       1      NA

data

dataframe <- data.frame(ID=c("ID1","ID2","ID3", "ID4"), 
          column1=c(1,NA,0,1), column2=c(1,0,0,1),column3=c(1,NA,NA,NA))
akrun
  • 874,273
  • 37
  • 540
  • 662