3

I have a problem which seems to me quite simple but I don't manage to solve it by myself. I've searched for the solution on StackOverflow, I guess it has already been solved by someone but I haven't found it yet.

I have a data frame based upon the merger of 5 data frames, which looks like that :

id | mag1 | mag2 | mag3
1 | name | name | name
2 | NA | NA | name
3 | NA | name | NA

With mag2 and mag3 there always is a name which is filled (there is no row with an NA in mag1, mag2 and mag3). I would like to change the value of mag1 in order that it is never empty and that it takes the value of the next non-empty cell.

I have imagined to use this kind of code :

db$mag1[is.na(db$mag1)] <- db$mag2
db$mag1[is.na(db$mag1)] <- db$mag3

With this code, it seems to me that for instance, in the second line, the replacement with the value of db$mag2 will leave mag1 unchanged (NA) and that the replacement with db$mag3 will change its value to "name". The second line shouldn't be activated if there is a non-NA value in mag2.

Now, here is the error I got :

Warning message:
In db$mag[is.na(db$mag1)] <- db$mag2 :
   number of items to replace is not a multiple of replacement length

I guess there is a very simple error in my code line, but I don't manage to see it. Any idea?

1 Answer 1

4

You have to use the logical index on both sides of the assignment <- so that the lengths are the same and corresponding elements are replaced.

 db$mag1[is.na(db$mag1)] <- db$mag3[is.na(db$mag1)]
 db
 #  id mag1 mag2 mag3
 #1  1 name name name
 #2  2 name <NA> name
 #3  3 <NA> name <NA>

data

 db <- structure(list(id = 1:3, mag1 = c("name", NA, NA), mag2 = c("name", 
 NA, "name"), mag3 = c("name", "name", NA)), .Names = c("id", 
 "mag1", "mag2", "mag3"), class = "data.frame", row.names = c(NA, 
 -3L))
2
  • Hi, I've tried it, it works for the first code line (to replace NA mag1 with mag2) but when I try the second line (db$mag1[is.na(db$mag1)] <- db$mag3[is.na(db$mag1)]) I get a new error ("Invalid factor level, NA generated")... I wonder why, as mag1, mag2 and mag3 are the same kind of cells so if it works for mag2 it should work exactly the same with mag3...
    – albert
    Dec 18, 2014 at 14:53
  • @albert The error says it all. You have factor columns. Suppose, the levels of the second column are not in the first, you will get that error. The best way is to create character columns. While you read the dataset using read.table, set stringsAsFactors=FALSE or in data.frame(
    – akrun
    Dec 18, 2014 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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