0

I am trying to merge two datasets like so

V1
 Berry

as the first data set and

V4   V6    V7   V1
Temp Temp  Temp Temp

To make

V4   V6    V7   V1
Temp Temp  Temp Temp
NA   NA    NA    Berry

I have tried using

test2<-merge(Session1t, temp2, by=temp1, all = TRUE)

Where temp1 is the column name V1 stored as a value. The problem I am having is I cannot explicitly state by="V1", because this is inside of a loop where the column names change for each iteration and I am unsure of how to merge the two datasets effectively. The closest I have gotten was merging them where it would create two V1 columns, but that is obviously not something that I can use.

www
  • 38,575
  • 12
  • 48
  • 84
Cali567
  • 1
  • 1
  • What if you drop the `by=temp1`? If they have same variable names, it will merge them... `merge(Session1t, temp2, all = T)` works for me, else post some data to make your problem reproducible. You might also want to read [how to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Tino Dec 28 '17 at 06:29
  • If I do that I get an undefined columns selected error. The first data set is only the one column, nothing else. I will look into making it more reproducible, but that might take me a bit. – Cali567 Dec 28 '17 at 06:38

1 Answers1

0

We can use the bind_rows function from the package.

# Create example data frame D1
D1 <- read.table(text = "V1
 Berry",
                 header = TRUE, stringsAsFactors = FALSE)

# Create example data frame D2
D2 <- read.table(text = "V4   V6    V7   V1
                 Temp Temp  Temp Temp",
                 header = TRUE, stringsAsFactors = FALSE)

# Load package
library(dplyr)

# Combine two data frames
D3 <- bind_rows(D2, D1)

D3
#     V4   V6   V7    V1
# 1 Temp Temp Temp  Temp
# 2 <NA> <NA> <NA> Berry

We can also use the rbind function from base R, which is similar to bind_rows, but we need to create columns not in D1or D2 with NA first.

# Get columns not match
NACol <- setdiff(names(D2), names(D1))

# Create columns based on NACol with NA
for (i in NACol){
  D1[[i]] <- NA
}

# Combine tow data frames
D3 <- rbind(D2, D1)
D3
#     V4   V6   V7    V1
# 1 Temp Temp Temp  Temp
# 2 <NA> <NA> <NA> Berry 
www
  • 38,575
  • 12
  • 48
  • 84