简体   繁体   中英

How to join two data sets in which one data set (1D) used as variables?

I want to join two datasets in which one dataset (contains 1 dimension) is transposed and used as variables to join the other.

For example:

df = data.frame(A=1:3, B=3:5)
df2 = data.frame(lab = letters[1:5], C = seq(letters[1:5]))

df2_transposed <- data.frame(t(df2))
colnames(df2_transposed ) <- t(df2)[1,]
df2_new <- df2_transposed[2,]

# there are certainly alternatives without transposing data

I want to see a dataset like this :

  A B a b c d e
1 1 3 1 2 3 4 5
2 2 4 1 2 3 4 5
3 3 5 1 2 3 4 5

I tried two methods:

Method 1

library(plyr)
new <- join(df, df2_new, by = NULL, type = "left", match = "all")

which produces

  A B    a    b    c    d    e
1 1 3 <NA> <NA> <NA> <NA> <NA>
2 2 4 <NA> <NA> <NA> <NA> <NA>
3 3 5 <NA> <NA> <NA> <NA> <NA>

Method 2

new1 =  vector('list',3)
for (i in 1:nrow(df)){
   new1[[i]] = cbind(df[i,], df2_new[1,])
}

new2 = data.frame(matrix(unlist(new1), nrow= nrow(df), byrow=T), stringsAsFactors = F)
colnames(new2) <- c(colnames(df), colnames(df2_new))

Which produces

  A B a b c d e
1 1 3 1 1 1 1 1
2 2 4 1 1 1 1 1
3 3 5 1 1 1 1 1

Still no luck solving this problem.

We can use cbind.fill

library(rowr)
cbind.fill(df, df2_new)
#  A B a b c d e
#1 1 3 1 2 3 4 5
#2 2 4 1 2 3 4 5
#3 3 5 1 2 3 4 5

If we want to do this with 'df/df2'

library(tidyverse)
deframe(df2) %>%
       as.list %>%
       as_tibble %>%  
       cbind.fill(df, .)

Or similar to @thelatemails' approach

data.frame(df, as.list(deframe(df2)))

Or with cbind from base R with a friendly warning

cbind(df, df2_new)

Or replicate the rows of 'df2_new' and cbind

cbind(df, df2_new[rep(1, nrow(df)),])

Using only base R, cbind a named list :

cbind(df, setNames(as.list(df2$C),df2$lab))
#  A B a b c d e
#1 1 3 1 2 3 4 5
#2 2 4 1 2 3 4 5
#3 3 5 1 2 3 4 5

Or the replacement form:

df[as.character(df2$lab)] <- as.list(df2$C)
df
#  A B a b c d e
#1 1 3 1 2 3 4 5
#2 2 4 1 2 3 4 5
#3 3 5 1 2 3 4 5

Or the non-replacement form of the replacement:

replace(df, as.character(df2$lab), as.list(df2$C))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM