Let's say we have additionaly information for a Data Frame, such as a new observation (row). We would like to add this to our existing data frame. In this article, we will learn how to append rows and columns to data frames in R.
To add a row to a data frame, we can use the
rbind method. The first argument will be our existing data frame and the second is the new row.
ad.names = c("Google", "Facebook", "Twitter") clicks = c(2000, 4000, 3000) df = data.frame(name=ad.names, clicks) row1 = data.frame(name="Instagram", clicks="2000") new.df = rbind(df, row1) print(new.df) # name clicks # 1 Google 2000 # 2 Facebook 4000 # 3 Twitter 3000 # 4 Instagram 2000
Now, let's say we have a new column of data. Maybe we have a vector of the impression count for each of our adds. We can add these to our data frame using the
$ property accessor and assining a new name.
impressions = c(10000, 20000, 30000, 20000) new.df$impressions = impressions print(new.df) # name clicks impressions # 1 Google 2000 10000 # 2 Facebook 4000 20000 # 3 Twitter 3000 30000 # 4 Instagram 2000 20000