Reputation: 2306
I would like to create a new column with letters, following the number of rows in the data frame.
Data:
set.seed(42)
df = data.frame(matrix(rnorm(20), nrow=10))
df
X1 X2
1 1.37095845 1.3048697
2 -0.56469817 2.2866454
3 0.36312841 -1.3888607
4 0.63286260 -0.2787888
5 0.40426832 -0.1333213
6 -0.10612452 0.6359504
7 1.51152200 -0.2842529
8 -0.09465904 -2.6564554
9 2.01842371 -2.4404669
10 -0.06271410 1.3201133
I could insert letters by setting the number of rows manually. I would like to do set it accordingly to the number of rows in the data frame.
df$label = as.character(LETTERS[1:10])
df
X1 X2 label
1 1.37095845 1.3048697 A
2 -0.56469817 2.2866454 B
3 0.36312841 -1.3888607 C
4 0.63286260 -0.2787888 D
5 0.40426832 -0.1333213 E
6 -0.10612452 0.6359504 F
7 1.51152200 -0.2842529 G
8 -0.09465904 -2.6564554 H
9 2.01842371 -2.4404669 I
10 -0.06271410 1.3201133 J
Upvotes: 2
Views: 572
Reputation: 2306
With dplyr
:
library(dplyr)
df %>%
mutate(label = LETTERS[row_number()])
Upvotes: 2
Reputation: 39667
You can use seq_len
with nrow
, but works only up to 26 rows.
df$label <- LETTERS[seq_len(nrow(df))]
In case you have more rows and want to repeat LETTEERS
:
df$label <- LETTERS[1 + seq(0, length.out = nrow(df)) %% 26]
Upvotes: 1