0

I have three different data frames that are similar in their columns such:

df1                  df2                  df3
Class  1  2  3       Class  1  2  3       Class  1  2  3
A      5  3  2       A      7  3  10      A      5  4  1
B      9  1  4       B      2  6  2       A      2  6  2
C      7  9  8       C      4  7  1       A      12 3  8

I would like to iterate through the three files and select the data from the columns with similar name. In other words, I want to iterate three times and everytime select data of column 1, then column 2, and then column 3 and merge them in one data frame.

To do that, I did the following:

  df1 <- read.csv(R1)
  df2 <- read.csv(R2)
  df3 <- read.csv(R3)
  df <- data.frame(Class=character(), B1_1=integer(), B1_2=integer(), B1_3=integer(), stringsAsFactors=FALSE) 
  for(i in 1:3){
    nam <- paste("X", i, sep = "") #here I want to call the column name such as X1, X2, and X3
    df[seq_along(df1[nam]), ]$B1_1 <- df1[nam] 
    df[seq_along(df2[nam]), ]$B1_2 <- df2[nam]
    df[seq_along(df3[nam]), ]$B1_3 <- df3[nam]
    df$Class <- df1$Class
  }

In this line df[seq_along(df1[nam]), ]$B1_1 <- df1[nam], I followed the solution from this but this produces the following error:

Error in `$<-.data.frame`(`*tmp*`, "B1_1", value = list(X1 = c(5L, 7L,  : 
  replacement has 10 rows, data has 1 

Do you have any idea how to solve it?

Adam Amin
  • 1,406
  • 2
  • 11
  • 23

0 Answers0