简体   繁体   English

将值作为新行添加到数据框中,但保留所有其他列 NA

[英]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 .我们首先需要将IDnumeric转换为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.

相关问题 如何在R中添加一个具有一个值和所有其他NA值的新行 - How to add a new row with one value and all other NA values in R 如何只保留行的最大值并将其他值转换为 NA? - How to keep only max value of row and convert other value to NA? 如何在跨多列的一行中保留最小值并使所有其他行值在 R 中为 0 - How to just keep the minimum value in a row across multiple columns and make all other row values 0 in R 仅当另外两个列也为NA时,才用值替换Dataframe列中的NA - Replace NA in a Dataframe Column with a Value Only when Two Other Columns Are Also NA 在 dataframe 中添加一行,并在 R 的特定列中添加值 - add a row to dataframe with value in specific columns in R 对某些列的跨行求和,如果全部为 NA,则保留 NA - summing acrossing rows for certain columns, keep NA if all NA 计算每一行的列明智总和并为数据框中的每个值添加新列 - Calculate column wise sum for each row & add new columns for each value in dataframe 将 dataframe 中的 NA 值替换为组内其他列的第一个或最后一个值 - Replacing NA value in dataframe by first or last value of other columns within group 为DataFrame中的所有列查找和替换NA值 - Find and replace values by NA for all columns in DataFrame 当`dplyr`中的所有列都是NA时过滤数据框 - Filter dataframe when all columns are NA in `dplyr`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM