WHB533
WHB533

Reputation: 3

How do I add columns to a data.frame

I am a newbie in R, Now I have an “a” with 25 rows and 3 columns. I want to add a column, and this column is going to be: rows 1-5 are going to be "A" and rows 6-10 are going to be "B"......, And then it goes up to the last row. Can automatic addition be implemented? I automatically named each of the five lines "A", "B", "C", "D"......, no matter how many lines there were in the original "a"

a<-matrix(c(1:75),nrow=25,ncol=3,byrow = T)
a
a<-as.data.frame(a)

Upvotes: 0

Views: 34

Answers (2)

AnilGoyal
AnilGoyal

Reputation: 26238

Alternate solution tidyverse way

library(tidyverse)

a %>% mutate(id = row_number()-1, 
             new_col = LETTERS[(id%/%5)+1]) %>%
  select(-id)

   V1 V2 V3 new_col
1   1  2  3       A
2   4  5  6       A
3   7  8  9       A
4  10 11 12       A
5  13 14 15       A
6  16 17 18       B
7  19 20 21       B
8  22 23 24       B
9  25 26 27       B
10 28 29 30       B
11 31 32 33       C
12 34 35 36       C
13 37 38 39       C
14 40 41 42       C
15 43 44 45       C
16 46 47 48       D
17 49 50 51       D
18 52 53 54       D
19 55 56 57       D
20 58 59 60       D
21 61 62 63       E
22 64 65 66       E
23 67 68 69       E
24 70 71 72       E
25 73 74 75       E

Note: It will add NA after 26x5 rows are exhausted.

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389325

You can use rep :

a$new_col <- LETTERS[rep(1:nrow(a), each = 5, length.out = nrow(a))]
a

#   V1 V2 V3 new_col
#1   1  2  3       A
#2   4  5  6       A
#3   7  8  9       A
#4  10 11 12       A
#5  13 14 15       A
#6  16 17 18       B
#7  19 20 21       B
#8  22 23 24       B
#9  25 26 27       B
#10 28 29 30       B
#11 31 32 33       C
#12 34 35 36       C
#...
#...

Upvotes: 1

Related Questions