I want to create a Data Frame with 1 row and n columns but the column names need to change with my n. So for example if my n = 3, I want a Data Frame with 1 Row and 3 columns and the column names should be A1 A2 A3.
Asked
Active
Viewed 219 times
-1
-
Have you tried anything? – camille Dec 28 '21 at 16:33
-
1Does this answer your question? [How to initialize empty data frame (lot of columns at the same time) in R](https://stackoverflow.com/questions/20501345/how-to-initialize-empty-data-frame-lot-of-columns-at-the-same-time-in-r) Also https://stackoverflow.com/q/50706183/5325862 – camille Dec 28 '21 at 16:39
2 Answers
0
ncol <- 3
df <- setNames(data.frame(matrix(nrow = 1, ncol = ncol)), paste0("A", seq(ncol)))
df
A1 A2 A3
1 NA NA NA

D.J
- 1,180
- 1
- 8
- 17
0
Step by step:
# define n
n <- seq(1:3)
# create dataframe
myData = data.frame(matrix(nrow = 1, ncol = length(n)))
# column names
columns <- paste0("A", n)
# bring together
names(myData) <- columns
myData
output:
A1 A2 A3
1 NA NA NA

TarJae
- 72,363
- 6
- 19
- 66