Here is my sample dataset:
mydata = data.frame (ID =c(1,2,3,4,5),
subject = c("His","Geo","Geo","His","Geo"),
age = c(21,24,26,23,26))
I would like to add a row at the top. I would like it to say "School 1" in the ID column while all other columns remain blank. The following is what I am looking for:
mydata = data.frame (ID =c("School 1",1,2,3,4,5),
subject = c(NA,"His","Geo","Geo","His","Geo"),
age = c(NA,21,24,26,23,26))
I have tried the following, but it ends up populating the value across all columns:
mydata <- rbind(c("School 1"), mydata)
I know the following code will get me what I want, but I would like to avoid having to list out NA's as my dataset has tons of columns
mydata <- rbind(c("School 1", NA,NA), mydata)
Any help is appreciated!
A possible solution, based on dplyr
. We first need to convert ID
from numeric
to character
.
library(dplyr)
mydata %>%
mutate(ID = as.character(ID)) %>%
bind_rows(list(ID = "School 1"), .)
#> # A tibble: 6 × 3
#> ID subject age
#> <chr> <chr> <dbl>
#> 1 School 1 <NA> NA
#> 2 1 His 21
#> 3 2 Geo 24
#> 4 3 Geo 26
#> 5 4 His 23
#> 6 5 Geo 26