Eric González
Eric González

Reputation: 485

How to avoid duplicated values uisng rbind and data.frame?

I want to merge values in a data frame.

My toy example is this one:

table1 <-c()

a <- data.frame("p.value" = c(0.01, 0.05), "Pos" = c(1, 2))
b <- data.frame("p.value" = 0.005, "Pos" = 1)

table1 <- rbind(table1,data.frame(a, b)) 

This is giving me this output:

> table1
p.value Pos p.value.1 Pos.1
1    0.01   1     0.005     1
2    0.05   2     0.005     1

But my desired output is:

> table1
p.value Pos p.value.1 Pos.1
1    0.01   1     0.005     1
2    0.05   2      NA       NA

Could you please tell me how I could avoid to have the duplicated values and fill with NAs?

Upvotes: 2

Views: 1320

Answers (3)

Thomas
Thomas

Reputation: 1302

To obtain your desired table1 without merging by Pos, you could merge by rownames:

tbl_a <- a %>% mutate(names = rownames(a))
tbl_b <- b %>% mutate(names = rownames(b))

table1 <- tbl_a %>% 
  full_join(tbl_b, by = "names")
table1

If you want to transform back to data.frame, use

table1 %>%
  select(-names) %>%
  as.data.frame

which results in exactly the data frame you posted

Upvotes: 2

Arienrhod
Arienrhod

Reputation: 2581

If you don't absolutely need the other Pos columns, you can use a left_join from tidyverse.

table1 <- rbind(table1, left_join(a, b, by=c("Pos"), suffix = c("", ".1")))

  p.value Pos p.value.1
1    0.01   1     0.005
2    0.05   2        NA

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

One way could be to make both the dataframes of same number of rows and then cbind

cbind(a, b[seq_len(nrow(a)), ])

#   p.value Pos p.value Pos
#1     0.01   1   0.005   1
#NA    0.05   2      NA  NA

Upvotes: 2

Related Questions