-3

I have merge two datasets on the variable Name in R. I need a way to combine the School.x and School.y columns so that the NA fields are filled in by the other column. I assume there is some easy way in R to do this- anyone have ideas?

Image of a sample of the merged data below (couldn't paste the table for some reason.)

enter image description here

Bonus if you can figure out how to make it so that if School.x and School.y both have a value, the merged column just takes the default value from School.x (For example, if Chloe was listed as attending Lincoln in School.x but Lincoln High in School.y, I just want the column to default to Lincoln.)

Thanks so much!

Rebecca Kuang
  • 63
  • 1
  • 4
  • 10
    Bonus if you can figure out how to post a reproducible example. [Here's a hint](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?s=1|12.5600) – Rich Scriven Nov 17 '15 at 06:17

1 Answers1

3

The following code should do the trick. I modified the third row of your sample data frame to be a case where both School.x and School.y have non NA values, to demonstrate the bonus part of your question.

df <- data.frame(Name=c("Adam", "Bob", "Jane", "Bill", "Chloe", "Mandy"),
                 School.x=c("Hillcrest", NA, "Irvington", NA, "Lincoln", NA),
                 School.y=c(NA, "Star Academy", "Star Academy", "Mission Hills", NA,
                            "Washington Middle"),
                 stringsAsFactors=FALSE)


# choose default value from 'School.x' in the case that both 'School.x' and
# 'School.y' have values
df$merged[!is.na(df$School.x) & !is.na(df$School.y)] <-
    df$School.x[!is.na(df$School.x) & !is.na(df$School.y)]

# replace NA values in 'School.x' with values from 'School.y' and vice-versa
df$merged[is.na(df$School.x)] <- df$School.y[is.na(df$School.x)]
df$merged[is.na(df$School.y)] <- df$School.x[is.na(df$School.y)]

> df
   Name  School.x          School.y            merged
1  Adam Hillcrest              <NA>         Hillcrest
2   Bob      <NA>      Star Academy      Star Academy
3  Jane Irvington      Star Academy         Irvington
4  Bill      <NA>     Mission Hills     Mission Hills
5 Chloe   Lincoln              <NA>           Lincoln
6 Mandy      <NA> Washington Middle Washington Middle
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360