Q:

How to copy data between columns based on duplicates in a single column

I have a dataset that looks like this:
names <- c("Smith, John", "Lu, Samantha", "Lu, Samantha", "Kumar, Vikram", "Kranski, Peter", "Kumar, Vikram")
data <- c("data1", "data2", "", "", "data3", "data4")
df <- data.frame(names, data, stringsAsFactors=FALSE)

I need to make sure all of the names have the data associated with them in the column data in their row. I therefore want to paste all the data points in data to duplicates but only when there is an empty cell. In other words, I want an output that looks like this:
names <- c("Smith, John", "Lu, Samantha", "Lu, Samantha", "Kumar, Vikram", "Kranski, Peter", "Kumar, Vikram")
data <- c("data1", "data2", "data2", "data4", "data3", "data4")
df <- data.frame(names, data, stringsAsFactors=FALSE)

I am then going to use df <- df[!duplicates(df$names),] to eliminate duplicates so I get a dataframe that looks like this:
names <- c("Smith, John", "Lu, Samantha", "Kranski, Peter", "Kumar, Vikram")
data <- c("data1", "data2", "data3", "data4")
df <- data.frame(names, data, stringsAsFactors=FALSE)

Does anyone know how I can do this?
Thanks in advance for your help!

A:

Assuming you have unique mappings from names to data in the rows that have a non-empty data field, you can do a left_join with the cleaned up version. This will generate a new column data_complete and you can then remove the original data column. Renaming at the end is optional.
library(dplyr)
left_join(df, df[df$data != "", ], 
          by = "names", suffix = c("_raw", "_complete")) %>% 
  select(names, data_complete) %>% 
  rename("data" = "data_complete")

You can also check whether your mappings are unique by checking the intermediate step:
left_join(df, df[df$data != "", ], 
          by = "names", suffix = c("_raw", "_complete")) %>% 
  filter(data_raw != "" & data_raw != data_complete)

