1

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!

jtscheirer
  • 13
  • 3
  • please share a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) – IceCreamToucan Jan 15 '21 at 18:59

2 Answers2

0

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   

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
  • Awesome, thank you! This did exactly what I was looking for. Turns out it was fairly simple and I just hadn't figured it out. – jtscheirer Jan 19 '21 at 21:15
0

It is quite easy.

Say we have an empty data frame with 3 columns and 2 rows like this:

df.a <- as.data.frame(matrix(nrow = 2, ncol = 3))

We then have a data frame with 3 columns and one row like this:

df.b <- as.data.frame(c("one","two","three"))

To assign 1-st row of df.b as column names to df.a we do:

names(df.b) <- df.b[,1]

Which means subset df.b taking it's first row - this will be character vector of 3 elements - exactly as many columns as we have to name. This vector we assign to the names of the columns in the other data frame. In your case it is 95 columns but as long column numbers match in both dataframes, it does not matter.

It is often handy to use this syntax when you want to correct column names - you basically do column name editing in place. For example names(df.a) <- gsub("\\.$", "", names(df.a) will remove trailing dot in column names (replace it with nothing).

r0berts
  • 842
  • 1
  • 13
  • 27
  • This is excellent, thanks! This worked for me too. Always great when there are multiple ways to solve a problem. – jtscheirer Jan 19 '21 at 21:15