[英]Add a value as a new row to a dataframe but keep all other columns NA
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.
我希望它在 ID 列中显示“学校 1”,而所有其他列保持空白。 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我知道下面的代码会让我得到我想要的,但我想避免列出 NA,因为我的数据集有很多列
mydata <- rbind(c("School 1", NA,NA), mydata)
Any help is appreciated!任何帮助表示赞赏!
A possible solution, based on dplyr
.基于
dplyr
的可能解决方案。 We first need to convert ID
from numeric
to character
.我们首先需要将
ID
从numeric
转换为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
You may rbind
two data frames.您可以
rbind
两个数据帧。
tmp <- setNames(data.frame('School 1', NA, NA), names(mydata))
rbind(tmp, mydata)
# ID subject age
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.