Reed
Reed

Reputation: 318

Replacing NA values with items in a list

I have a data frame where with 22 columns, and some where around 600 rows. In one of the columns I have a bunch of NA values, and I want to replace those with items from a list so I can use that column as ID's however I have yet to find a solution

The simple replace(data$Tag_Number, is.na(data$Tag_Number, pse.id)) does not work (where pse.id = (5000:6000)).

I also tried:

>for(i in length(data[,1])){
  if(is.na(data$Tag_Number[i])==TRUE){
    new.id = pse.id[[i]]
    data$Tag_Number[i] = new.id
  }
}

It seems that R really does not want me writing over the NA value. any ideas?

Upvotes: 1

Views: 1931

Answers (1)

farnsy
farnsy

Reputation: 2470

I don't see any problem just using the regular assignment operator. To answer your more general statement of the question:

> x <- 1:10
> y <- c(30, 31, NA, 41, 46, NA, 55, NA, 66, 80)
> df <- data.frame(x, y)
> New <- 1000:2000
> df$y[is.na(df$y)] <- New[1:sum(is.na(df$y))] 
> df
    x    y
1   1   30
2   2   31
3   3 1000
4   4   41
5   5   46
6   6 1001
7   7   55
8   8 1002
9   9   66
10 10   80

Make sure the number of elements of New that you are assigning is equal to the number of NA values being overwritten.

Upvotes: 1

Related Questions