ReRed
ReRed

Reputation: 373

R adding element to Dataframe at specific position

I want to add a row to a dataframe in R at a specific position. I am aware that there are solutions for this on this site, yet they don't seem to work. I know rbind is rather slow, but given that I only need to do it for a single element it doesn't matter:

Example:

vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,], data.frame("value"=5000), 
                            vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),])

The desired result is obviously 1,2,3,4,5,5000,6,7,8,9, yet I get 1,5000,6. Where is my mistake?

Upvotes: 0

Views: 571

Answers (2)

akrun
akrun

Reputation: 887213

We can use add_row to add a specific row at a location

library(tibble)
add_row(vector_labour_brexit.m , .before = 6, value = 5000)
#   value
#1      1
#2      2
#3      3
#4      4
#5      5
#6   5000
#7      6
#8      7
#9      8
#10     9

The issue in the OP's code was due to drop = TRUE by default when there is a single column or row, it drops the dimensions

vector_labour_brexit.m[1:5,]

If we add drop = FALSE while subsetting, it would work

Upvotes: 1

MrFlick
MrFlick

Reputation: 206253

Your problem is that when indexing data.frames that only have one column in the result, the returned value is simplified to a vector which confuses rbind. To be safe you can do

vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,,drop=FALSE],
              data.frame("value"=5000), 
              vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),,drop=FALSE])

Upvotes: 1

Related Questions