Reputation: 19
Suppose I have the following 2 dataframes
dfx <- data.frame(z = rpois(10,2), q = rpois(10,2), p = rpois(10,2), k = rpois(10,2), t = rpois(10,2))
dfy <- data.frame(a = rpois(10,2), b = rpois(10,2), c = rpois(10,2), d = rpois(10,2), e = rpois(10,2))
with dfx consistent of a bunch of x-values and dfy consisting of a bunch of y-values - z partner to a, q partner to b, etc.). I want to create a dataframe where: 1) Every column is a x,y coordinate, so that it looks as follows
column1: column2 column3: column4: column5:
z1,a1 q1,b1 p1,c1 k1,d1 t1,e1
z2,a2 q2,b2 p2,c2 k2,d2 ...
z3,a3 q3,b3 p3,c3 ... ...
z4,a4 q4,b4 ... ... ...
... ...
etc.
Any help is appreciated.
Upvotes: 1
Views: 1970
Reputation: 887148
We can do a paste
out <- data.frame(Map(paste, dfx, dfy, MoreArgs = list(sep=",")))
names(out) <- paste0("column", seq_along(out))
out
# column1 column2 column3 column4 column5
#1 2,2 1,6 1,0 1,0 1,5
#2 3,2 3,3 1,2 2,2 0,1
#3 3,3 1,0 2,2 1,3 1,1
#4 2,2 5,3 2,4 4,1 1,0
#5 3,1 4,1 1,3 1,1 0,1
#6 4,1 1,2 3,2 2,1 1,5
#7 5,2 5,0 0,2 4,3 2,1
#8 3,0 2,5 4,2 5,4 4,2
#9 3,3 3,2 0,3 5,1 0,3
#10 4,2 2,2 0,1 4,3 5,1
Or if it needs to be a list
column
Map(list, dfx, dfy)
Or if it is converted to matrix
, paste
can be directly applied
array(paste(as.matrix(dfx), as.matrix(dfy), sep=","), dim = dim(dfx),
dimnames = list(NULL, paste0("column", seq_along(dfx))))
With tidyverse
, we can use map2
library(purrr)
library(stringr)
map2_df(dfx, dfy, str_c, sep=",") %>%
rename_all(~ str_c('column', seq_along(.)))
Upvotes: 1
Reputation: 39858
One base R
option could be:
df <- data.frame(matrix(paste(unlist(dfx), unlist(dfy), sep = ","), dim(dfx)))
names(df) <- paste0("column", 1:length(df))
column1 column2 column3 column4 column5
1 1,1 2,2 3,2 2,0 0,3
2 1,3 1,4 3,1 2,1 1,4
3 2,0 0,4 4,1 2,1 2,4
4 3,3 3,3 2,2 1,3 1,2
5 2,2 2,3 0,1 0,0 0,3
6 1,0 0,1 2,4 5,3 4,3
7 0,1 1,3 2,3 0,2 4,3
8 0,1 0,2 1,4 2,3 1,1
9 1,6 2,3 1,0 5,3 0,2
10 3,1 1,2 0,3 3,2 2,1
Upvotes: 1