Add a Vector to a Column of a Dataframe

Sorry about this one but I can't find an easy solution to this.

I have a data frame:

>bla<-c(1)
>df<-data.frame(bla)
>df

bla
1   1

I want to append values to the bottom of the column (hence not create a new one, as explained here). For instance, get:

bla
1   1
2   2
3   3
4   4
5   5

I tried:

df[2,1]<-c(2,3,4,5)
df[,1]<-c(2,3,4,5)

but I get:

Error in `[<-.data.frame`(`*tmp*`, 2, 1, value = c(2, 3, 4, 5)) : 
  replacement has 4 rows, data has 1

Maybe dataframes are not appropriate and I should try with matrixes instead? Any suggestion would be much appreciated! :)

3

2 Answers

You need to convert c(2,3,4,5) to a data frame then use rbind to join the rows as @Ananda Mahto did in his comment

df <- rbind(df, data.frame(bla = c(2,3,4,5)))

Where 'bla' is the name of the column in df

Another option if you know the final dimensions in advance is just to create an empty dataframe of the given size and then append rowwise:

blah <- data.frame(matrix(NA, nrow=N, ncol=M))
    for (i in 1:N) {
      yourResults <- yourFunction()
      blah[i,] <- yourResults
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest