-3

I have a data frame built as such:

dput(au.weighted.scores)

    structure(list(AUDIT = c(0.283333333333333, 0.283333333333333, 
    0.183333333333333, 0.3, 0.2625), CORC = c(0.2, 0, 0.76, 0.82, 
    0.545), GOV = c(0.82, 0.82, 0.74, 0.66, 0.76), PPS = c(0.2, 0.2, 
    0.2, 0.266666666666667, 0.216666666666667), TMSC = c(0.525, 0.525, 
    0.25, 0.158333333333333, 0.189583333333333), TRAIN = c(0.233333333333333, 
    0.233333333333333, 0.216666666666667, 0.266666666666667, 0.2375
    )), .Names = c("AUDIT", "CORC", "GOV", "PPS", "TMSC", "TRAIN"
    ), row.names = c(NA, -5L), class = "data.frame")

I need to add a column of names that accompany the rows of this data frame. The column is c("Group1", "Group2", "Group3", "Group4", "Group5").

How can I add this column of names in with it's own column name like "Group_Name"?

The end result would look like this:

au.weighted.scores

 Group_Name     AUDIT  CORC  GOV       PPS      TMSC     TRAIN
1 Group1        0.2833333 0.200 0.82 0.2000000 0.5250000 0.2333333
2 Group2        0.2833333 0.000 0.82 0.2000000 0.5250000 0.2333333
3 Group3        0.1833333 0.760 0.74 0.2000000 0.2500000 0.2166667
4 Group4        0.3000000 0.820 0.66 0.2666667 0.1583333 0.2666667
5 Group5        0.2625000 0.545 0.76 0.2166667 0.1895833 0.2375000
Zach
  • 1,316
  • 2
  • 14
  • 21
  • 4
    I have the feeling someone has asked this before... – Damiano Fantini Aug 27 '17 at 04:56
  • 1
    `au.weighted.scores %>% mutate(Group_Name = c("Group1", "Group2", "Group3", "Group4", "Group5"))` – alistaire Aug 27 '17 at 04:57
  • 2
    Possible duplicate of [How to add new column to an dataframe (to the front not end)?](https://stackoverflow.com/questions/19508256/how-to-add-new-column-to-an-dataframe-to-the-front-not-end) or this one: https://stackoverflow.com/questions/10150579/adding-a-column-to-a-data-frame – mt1022 Aug 27 '17 at 05:24

2 Answers2

2

We can create the vector with paste and cbind it to the original dataset

cbind(Group_Name = paste0("Group", seq_len(nrow(au.weighted.scores))), au.weighted.scores)
#  Group_Name     AUDIT  CORC  GOV       PPS      TMSC     TRAIN
#1     Group1 0.2833333 0.200 0.82 0.2000000 0.5250000 0.2333333
#2     Group2 0.2833333 0.000 0.82 0.2000000 0.5250000 0.2333333
#3     Group3 0.1833333 0.760 0.74 0.2000000 0.2500000 0.2166667
#4     Group4 0.3000000 0.820 0.66 0.2666667 0.1583333 0.2666667
#5     Group5 0.2625000 0.545 0.76 0.2166667 0.1895833 0.2375000

Note that we used cbind so that the column will be the in the first position as in the expected output

akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Simple and effective. I ended up using it this way: au.weighted.scores <- cbind(AU = paste0(au.names), au.weighted.scores) \\ where au.names is a character vectors of the names I wanted to include. – Zach Aug 27 '17 at 05:28
2

If you just want the simplest possible way, I would use this:

au.weighted.scores$Group_Name <- paste0("Group", 1:5)

Stedy
  • 7,359
  • 14
  • 57
  • 77