Hello i am new to R programming and i am stuck with one problem. I would like to combine 2 dataframe into a new one in this way. First column of first dataframe, first column of second dataframe and then the third column of the new dataframe should be the difference between the 2 columns before, and iterate the process for all the columns of the dataframe ( they have same size of course). The crucial point is that the new columns should have their name unchanged.... this is where i get stuck. Please help meeee

i tried to iterate a for loop and combine through cbind but then i don't know how to leave the column names unchanged

2

There are 2 best solutions below

0
On

If you cbind the data.frames you will get the original column names which I think was your goal. You can then rearrange the columns with a trick that depends on how R matrices behave when "unfolded" with the c() function:

t( matrix(1:6,,2) )  # could also use matrix(1:6, 2, byrow=TRUE)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
> c( t( matrix(1:6,,2) ) ) # third arg to `matrix` is "ncol"
[1] 1 4 2 5 3 6

So make such a matrix that depends on twice the length of the dataframes and then use it to reorder the result of cbind()-ing:

    df_both <- cbind(dat1, dat2)[ c( t( matrix(1:(2*length(dat1), ,2) ) ) 
0
On

Use the code

cbind(data1, data2, data3)[order(rep(seq(data1), 3))]

Explanation:

You said you have two datasets data1 and data2, and a 3rd dataset which is the difference of the two datasets. Here is a quick way to go about it

data1 <- head(iris[1:3])
data2 <- head(trees)
data3 <- data1 - data2
names(data3) <- paste0(names(data1), '_', names(data2))

Having the data above, to get the desired output we could simply do:

cbind(data1, data2, data3)[order(rep(seq(data1), 3))]