for reasons that have to do with checking an error in ArcGis, where my data is going, I need to add a row at the top that contains dummy variables, which I would like to be Column1:Column(n)
For example, I have this:
ID A B C
1 A 1 8 set1
2 A 2 9 set2
3 B 3 10 set1
4 B 4 11 set2
5 B 5 12 set3
6 C 6 13 set1
7 C 7 14 set2
I would like this:
ID A B C
1 Column1 Column2 Column3 Column4
2 A 1 8 set1
3 A 2 9 set2
4 B 3 10 set1
5 B 4 11 set2
6 B 5 12 set3
7 C 6 13 set1
8 C 7 14 set2
I understand that this would make some numeric columns into character. Some dummy data from dput is below. As a note, my real data set has many more actual columns.
dput(df)
structure(list(ID = c("A", "A", "B", "B", "B", "C", "C"), A = c(1,
2, 3, 4, 5, 6, 7), B = c(8, 9, 10, 11, 12, 13, 14), C = c("set1",
"set2", "set1", "set2", "set3", "set1", "set2")), class = "data.frame", row.names = c(NA,
-7L))
>Solution :
With tidyverse
, use add_row
after converting the columns to character
library(dplyr)
library(tibble)
library(stringr)
df %>%
mutate(across(everything(), as.character)) %>%
add_row(!!! setNames(str_c("Column", seq_along(.)), names(df)), .before = 1)
-output
ID A B C
1 Column1 Column2 Column3 Column4
2 A 1 8 set1
3 A 2 9 set2
4 B 3 10 set1
5 B 4 11 set2
6 B 5 12 set3
7 C 6 13 set1
8 C 7 14 set2