1

I have two df which look like:

>df1
name   time    date
Dan    01:00    Apr-17
Ann    02:00    Apr-17

>df2
name   time
Joe    03:00
Bob    04:00

>out
name   time
Dan    01:00
Ann    02:00
Joe    03:00

I want to combine one row from df1 into df2 WITHOUT creating new columns. Furthermore the data under names are the rownames and should not be overwritten. My actual dataframes have ~800 and 99 columns respectively.

Ive tried following answers in previous similar questions but I cannot get my desired outcome, including rbind, bind_rows, rbind.fill. These work to some degree but always remove my rownames

rbind.fill(df1, df2[colnames(df2) %in% colnames(df2)])
rbind(df2, df1[1,names(df1)])
bind_rows(df1[1,], df2)
AudileF
  • 436
  • 2
  • 10
  • `rbind.fill` is not a base R function. Please include the names of any packages that you are using in your code. – lmo Jul 26 '17 at 11:38

2 Answers2

1

You were very close with your attempts.

rbind.fill(df1, df2[colnames(df2) %in% colnames(df2)])

basically says: bind df1 to df2, but take only the columns from df2 that are also in df2.

But that is not what you want to do. Try:

rbind(df1[colnames(df1) %in% colnames(df2)], df2)

Which says: bind df1 to df2, but take only the columns from df1 that are also in df2.

Result:

  name  time
1  Dan 01:00
2  Ann 02:00
3  Joe 03:00
4  Bob 04:00

Or only add the rows from df2 where name=="Joe"

rbind(df1[colnames(df1) %in% colnames(df2)], df2[df2$name=="Joe",])

Result:

  name  time
1  Dan 01:00
2  Ann 02:00
3  Joe 03:00
Florian
  • 24,425
  • 4
  • 49
  • 80
  • Thanks Florian. Is there a way to specify a particular row from df2 to merge with df1? – AudileF Jul 26 '17 at 11:02
  • I am not really sure what you mean by that. The output seems to match your requested output? – Florian Jul 26 '17 at 11:04
  • It does the trick right enough. I am just having difficulty in including a specific row and I was hoping to coerce it into df2. – AudileF Jul 26 '17 at 11:08
  • Ive tried these and I get the following error `i evaluates to a logical vector length 845 but there are 112 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.` – AudileF Jul 26 '17 at 11:22
  • I modified my answer to show how to do it. Make sure that you d not accidently do `df2[df1$name=="Joe",]`, your error sounds like that might be the problem. Otherwise consider opening a new question for that specific issue, and please take a look [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Florian Jul 26 '17 at 11:27
0

Here is an option using tidyverse

library(tidyverse)
bind_rows(df1[-3], df2)
#   name  time
#1  Dan 01:00
#2  Ann 02:00
#3  Joe 03:00
#4  Bob 04:00
akrun
  • 874,273
  • 37
  • 540
  • 662