Skip to content

Add blank rows to a dataframe

3 messages · Bert Jacobs, David Winsemius, arun

#
Hi,

I have a vector that looks like this:
RowSel <-c(0,1,0,1,2,3,0,5,5)

Now I want to select rows from a specific dataframe DF based on that vector
like this:
SubDF <- DF[RowSel,]

So this works fine, but I was wondering how I could add blank rows add the
locations in the vector where there is a zero:
So the final dataframe should look like this:

SubDF
[1] blank row
[2] row 1
[3] blank row
[4] row 1 
[5] row 2
[6] row 3
[7] blank row
[8] row 5
[9] row 5

Do I have to use a loop for this or does there exist a straight forward
function option.

Thx,
Bert
#
On Jun 8, 2013, at 4:09 AM, Bert Jacobs wrote:

            
NA's in the selection vector will retrun an NA row, so convert those zeros to NA's :
'data.frame':	9 obs. of  2 variables:
 $ A: num  0 3 9 0 2 0 1 0 1
 $ B: int  1 1 1 2 2 3 3 4 4
A B
1   0 1
1.1 0 1
5   3 1
9   9 1
6   2 2
6.1 2 2
A  B
NA   NA NA
1     0  1
NA.1 NA NA
1.1   0  1
5     3  1
9     9  1
NA.2 NA NA
6     2  2
6.1   2  2
#
RowSel <-c(0,1,0,1,2,3,0,5,5)
set.seed(24)
DF<- as.data.frame(matrix(sample(1:40,45,replace=TRUE),ncol=5))
RowSel[!as.logical(RowSel)]<-NA
DF[RowSel,]
#???? V1 V2 V3 V4 V5
#NA?? NA NA NA NA NA
#1??? 12 11 21 24 30
#NA.1 NA NA NA NA NA
#1.1? 12 11 21 24 30
#2???? 9 25? 6 26 26
#3??? 29 15? 4? 2 28
#NA.2 NA NA NA NA NA
#5??? 27 27 30 10 19
#5.1? 27 27 30 10 19


A.K.



----- Original Message -----
From: Bert Jacobs <bert.jacobs at figurestofacts.be>
To: r-help at r-project.org
Cc: 
Sent: Saturday, June 8, 2013 7:09 AM
Subject: [R] Add blank rows to a dataframe

Hi,

I have a vector that looks like this:
RowSel <-c(0,1,0,1,2,3,0,5,5)

Now I want to select rows from a specific dataframe DF based on that vector
like this:
SubDF <- DF[RowSel,]

So this works fine, but I was wondering how I could add blank rows add the
locations in the vector where there is a zero:
So the final dataframe should look like this:

SubDF
[1] blank row
[2] row 1
[3] blank row
[4] row 1 
[5] row 2
[6] row 3
[7] blank row
[8] row 5
[9] row 5

Do I have to use a loop for this or does there exist a straight forward
function option.

Thx,
Bert

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.