-1

I have a dada frame this is a small part:

namess[270:285,]
    first_name   last_name
270          R       Horne
271          T           H
272          A      McEvoy
273   Aumoitte        <NA>
274      Johin        <NA>
275  Waydelick        <NA>
276   Vigneron        <NA>
277  Sautereau        <NA>
278      Johin        <NA>
279   Aumoitte        <NA>
280    Georges Taillandier
281    Fernand        Sanz
282       John        Lake
283      Louis     Bastien
284      Louis  Hildebrand
285    Daumain        <NA>

I would like to replace every NA value in the column named last_name with the value in the column first_name. I saw a similar post in this is the link

Replace NA in column with value in adjacent column

I tried using what they suggeted

namess$last_name[is.na(namess$last_name)] <- as.character(namess$last_name[is.na(namess$last_name)])

It didn't change anything, both of the columns are character type so its not a problem of being a factor type variable

Community
  • 1
  • 1
Lee
  • 129
  • 7
  • You are replacing the NA values with themselves. Try `namess$last_name[is.na(namess$last_name)] – dww Jul 29 '16 at 22:56
  • 1
    This has already been answered [here](http://stackoverflow.com/questions/15629885/replace-na-in-column-with-value-in-adjacent-column?rq=1) – Richard Border Jul 30 '16 at 00:11

2 Answers2

2

We can use data.table. Convert the 'data.frame' to 'data.table' (setDT(namess)), in the i, we use the logical condition (is.na(last_name)) and assign (:=) those elements in 'first_name' that corresponds to the condition to 'last_name'.

library(data.table)
setDT(namess)[is.na(last_name), last_name := first_name]
namess
#    first_name   last_name
# 1:          R       Horne
# 2:          T           H
# 3:          A      McEvoy
# 4:   Aumoitte    Aumoitte
# 5:      Johin       Johin
# 6:  Waydelick   Waydelick
# 7:   Vigneron    Vigneron
# 8:  Sautereau   Sautereau
# 9:      Johin       Johin
#10:   Aumoitte    Aumoitte
#11:    Georges Taillandier
#12:    Fernand        Sanz
#13:       John        Lake
#14:      Louis     Bastien
#15:      Louis  Hildebrand
#16:    Daumain     Daumain
akrun
  • 674,427
  • 24
  • 381
  • 486
0

ifelse should give you what you're looking for here, though I can't say for certain without a reproducible example:

namess$last_name <- ifelse(is.na(namess$last_name), namess$first_name, namess$last_name)

nickbloom
  • 36
  • 1
  • 4
  • A more `R` way of doing this would be to utilize subsetting--see the other answer linked in the comments above. – Richard Border Jul 30 '16 at 00:13
  • You're right — I suggested `ifelse` because I think it's a bit more legible, and its lack of repetition doesn't lend itself quite as much to the kinds of copy/pasting errors that led OP astray in the first place. – nickbloom Jul 30 '16 at 00:45