Reputation: 455
I am trying to add an empty row to an existing populated Dataframe.
I am using the below procedure for this, but I do not want to see NA values in the empty row, just need some blank row.
Existing data frame:
abc
site control test delta pval
1 US15376 3.15% 3.2% 1.59% 0.0022
empty matrix:
empty=matrix(c(rep.int(NA,length(abc))),nrow=1,ncol=length(abc))
colnames(empty) = colnames(abc)
rbind(abc, empty)
site control test delta pval
1 US15376 3.15% 3.2% 1.59% 0.0022
2 NA NA NA NA NA
Can anyone help me with this?
Upvotes: 31
Views: 67087
Reputation: 43
If you are using a data.table
-object from the widely used package data.table
, you can use a method of binding a copy of the last row with the original, and turning it into NA's.
dt <- rbind(dt, dt[nrow(dt), ])
dt[nrow(dt), ] <- NA
This can also be extended to insert the row of NA's to any spot:
i <- 5
dt <- rbind(dt[1:i, ], dt[i:nrow(dt), ])
dt[i, ] <- NA
The previously mentioned simpler method of using rbind(dt, NA)
does not work when binding data.table
-objects. You would need to define a new matrix, data.frame or data.table of row of NA's with the corresponding column names to the original table, but the above solution is easier.
Upvotes: 0
Reputation: 131
tibble´s add_row should do the job. And if after that you want to get rid of NAs, one approach is to use dplyr´s mutate_all
library(tidyverse)
abc %>%
add_row() %>%
mutate_all(~replace(., is.na(.), ""))
Upvotes: 2
Reputation: 2636
Here is a version vor tidyverse that can be included in a pipeline:
library(tidyverse)
df %>%
bind_rows(set_names(rep(NA, ncol(.)), colnames(.)))
On a more philosophical note, "appending an empty row" is something one might want to do when working with (other) statistical software, but I can't think of instances where it aligns well with R's way of doing things. In other words, while it can be done in R, I think that if you are facing this problem, this points to more optimizing potential in your R workflow.
Upvotes: 1
Reputation: 734
This one that was in the comments just worked perfectly for adding an empty row in my data frame:
#before
df
site control test delta pval
1 US15376 3.15% 3.2% 1.59% 0.0022
df[nrow(df)+1,] <- NA
#after
df
site control test delta pval
1 US15376 3.15% 3.2% 1.59% 0.0022
2 NA NA NA NA NA
Upvotes: 54