0

I am trying to amalgamate two rows together so that the output is best of both worlds. I have read through some of the solutions using ddply or aggregate, however they work only with numeric data.

Below is an example of what I am trying to do.

Input:

x <- c("Yemen", 1, NA, NA, 4, 5, "Six")
y <- c("Yemen", NA, "B", 3, NA, 6, "Six")

DF <- as.data.frame(rbind(x,y))
colnames(DF)[1] <- c("CNTRY")

Output

"Yemen", 1, "B", 3, 4, 5, "Six"

where the key is CNTRY

Ideally, I should be able to choose whether to retain value of x or y if they are different.


Edit 1:

The solution should work on a data frame DF in this example and not x & y. My data frame has multiple accounts which are duplicated and I am trying to merge all of the rows that have more than one instance but share the account (key).

zx8754
  • 52,746
  • 12
  • 114
  • 209
Drj
  • 1,176
  • 1
  • 11
  • 26

2 Answers2

2

We can use coalesce function from dplyr

library(dplyr)
coalesce(x,y)
#[1] "Yemen" "1"     "B"     "3"     "4"     "5"     "Six"  
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Using fill from tidyr package:

# dummy data with 2 countries to group on
x <- c("Yemen", 1, NA, NA, 4, 5, "Six")
y <- c("Yemen", NA, "B", 3, NA, 6, "Six")
xx <- c("XXX", 3, NA, 33, 4, 7, "Four")
yy <- c("XXX", 2, "B", NA, NA, NA, NA)
DF <- as.data.frame(rbind(x,y,xx,yy))
colnames(DF)[1] <- c("CNTRY")

# using tidyr fill function up and down
library(dplyr)
library(tidyr)

DF %>% group_by(CNTRY) %>% 
  fill_(colnames(DF), .direction = "down") %>% 
  fill_(colnames(DF), .direction = "up") %>% 
  slice(1)

# Source: local data frame [2 x 7]
# Groups: CNTRY [2]
# 
#    CNTRY     V2     V3     V4     V5     V6     V7
#   <fctr> <fctr> <fctr> <fctr> <fctr> <fctr> <fctr>
# 1    XXX      3      B     33      4      7   Four
# 2  Yemen      1      B      3      4      5    Six
zx8754
  • 52,746
  • 12
  • 114
  • 209