Reputation: 436
I am creating data.frames with by_group. Now the number of rows depends on the dataset. Some have more rows than others. But i always need the same number. Is there a more efficient way for doubling the dataset by adding the same number of rows, but with empty values?
#add empty rows to dataframe
library(dplyr)
var1 <- 1:10
var2 <- c(1,1,1,1,0,1,0,1,1,0)
var3 <- rep(3, 10)
dat <- data.frame (var1, var2, var3)
View(dat)
dat2 <- data.frame (var1=rep(NA, 10), var2=rep(NA, 10), var3=rep(NA, 10))
bind_rows(dat, dat2)
Upvotes: 2
Views: 13128
Reputation: 299
This could work
dat[ NROW(dat)+ NROW(dat),] <- NA
Assuming you want to double the rows of dataframe dat and assign additional rows with NA.
Upvotes: 1
Reputation: 46
This should allow you to double the number of rows by creating a matrix that has the same number of columns and rows as the original data frame, giving it the same names as the original data frame, then binding the rows.
library(dplyr)
var1 <- 1:10
var2 <- c(1,1,1,1,0,1,0,1,1,0)
var3 <- rep(3, 10)
dat <- data.frame (var1, var2, var3)
dat2 <- data.frame(matrix(nrow = nrow(dat), ncol = ncol(dat)))
names(dat2) <- names(dat)
bind_rows(dat, dat2)
Upvotes: 3