How to insert rows at a specific place in a data frame?

I have a data frame, and would like to insert multiple (5) rows of all NA's at a specific place. I want to do this so when I make a heatmap, the program will put a thin grey line at this given point (When the value is blank or NA, the function just prints a grey space)

Example:

df <- data.frame(
  A = c(2,1,2,0,0,1),
  B = c(4,5,3,0,1,3),
  C = c(1,0,2,0,7,4),
  D = c(3,2,1,0,0,0)
)
row.names(df) <- c('one','two','three', 'four', 'five', 'six')
df

      A B C D
one   2 4 1 3
two   1 5 0 2
three 2 3 2 1
four  0 0 0 0
five  0 1 7 0
six   1 3 4 0

I want to put 5 rows of blank after four, or df[4, ]

Result:

df
    A  B  C  D
1   2  4  1  3
2   1  5  0  2
3   2  3  2  1
4   0  0  0  0
5  NA NA NA NA
6  NA NA NA NA
7  NA NA NA NA
8  NA NA NA NA
9  NA NA NA NA
10  0  1  7  0
11  1  3  4  0

Also I wanted to clarify, I dont want an NA string, but rather a blank value, which I think R enters as NA. Is that right?

Thanks so much!

df <- rbind(df[1:4, ], df[1:5, ] * NA, df[5:6, ])
2 Likes

That works they way I think the OP needs it to work (NA, rather than ""), but to give actual blanks (and avoid the row numbering glitch)

> blank <- c("","","","")
> top <- head(df,4)
> bottom <- tail(df,2)
> df.new <- rbind(top,blank,blank,blank,blank,bottom)
> rownames(df.new) <- seq(1,nrow(df.new),1)
> df.new
   A B C D
1  2 4 1 3
2  1 5 0 2
3  2 3 2 1
4  0 0 0 0
5         
6         
7         
8         
9  0 1 7 0
10 1 3 4 0

(Would've posted a reproducible example, called a reprex for for some reason it objected to the code.)

1 Like

You guys are the greatest thanks so much and happy hollidays. It works perfectly

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.