Search code examples
rappenddata-cleaningrbind

Append df containing column names to separate df without column names but corresponding datapoints


I'm essentially trying to add column names to a dataframe that does not have them. I have two dataframes, one of which has dimensions 1 x 95 (1 row containing 95 values that are column names that correspond to the 95 columns of the second df, which has dimensions of 146048 x 95 but no column names). I can't use rbind because the two df's obviously don't have the same column names, and for some reason when I use 'append' it doubles the number of columns in the resulting df (dimensions = 146048 x 190). Does anybody know why this is happening when I use 'append'? And can anybody suggest a solution that will achieve what I'm trying to do?

Thanks!


Solution

  • How about something like this. In the example below, x is a data frame and vn is also a data frame, but its sole row contains variable names for x. You can use setNames() on x to change its names to the first row of vn.

    x <- matrix(rnorm(10), ncol=5)
    x <- as.data.frame(x)
    x
    #          V1       V2        V3        V4         V5
    # 1 0.1600919 1.375629 0.2838454  1.403162  0.7560366
    # 2 0.3596158 1.594954 0.6369160 -1.368186 -0.2590074
    vn <- matrix(paste("var", 1:5, sep="_"), nrow=1)
    vn <- as.data.frame(vn)
    x <- setNames(x, vn[1,])
    x
    #       var_1    var_2     var_3     var_4      var_5
    # 1 0.1600919 1.375629 0.2838454  1.403162  0.7560366
    # 2 0.3596158 1.594954 0.6369160 -1.368186 -0.2590074