Search code examples
rlistdataframenamescol

Setting column names of dataset with contents of list


I read a table with data TestTR and one list with the corresponding column names Headrs. Now I want to set the column names of TestTR with the contents of Headrs:

TestTR:
 V1  V2  V3
 2   20   200
 1   10   100
 3   30   300

 Headrs: 
 Name1  Name2   Name3

This is what it should look like:

 Name1  Name2   Name3
 2   20   200
 1   10   100
 3   30   300

This is my code:

TestTR <- read.table(file="C:/Users/Sabine/Downloads/UCI_HAR_Dataset/mini_tr.txt", nrows=2)  
Headrs <- read.table(file="C:/Users/Sabine/Downloads/UCI_HAR_Dataset/features.txt", nrows=3)

 colnames(TestTR) <- Headrs

  print (class(Headrs)) #  gives me    "data.frame"
  print (dim(Headrs))   #  gives me     3   2
  print (Headrs)
   V1                V2
   1  1 tBodyAcc-mean()-X
   2  2 tBodyAcc-mean()-Y
   3  3 tBodyAcc-mean()-Z       

It looks like the above (actually the names are not name1, Name2, Name3--I simplified here).


Solution

  • This should work:

    colnames(TestTR) <- c(names(Headrs))