Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 101
4.3.8.4 Modifying Data Frames Add Columns to a Data-frame
ОглавлениеTypically, the variables are in the columns and adding a column corresponds to adding a new, observed variable. This is done via the function cbind()
.
cbind()
# Expand the data frame, simply define the additional column: data_test$End_date <- as.Date(c(“2014-03-01”, “2017-02-13”, “2014-10-10”, “2015-05-10”,“2010-08-25”)) print(data_test) ## Name Gender Score Age End_date ## 1 Piotr Male 80 42 2014-03-01 ## 2 Pawel Male 88 38 2017-02-13 ## 3 <NA> Female 92 26 2014-10-10 ## 4 Lisa Female 89 30 2015-05-10 ## 5 Laura Female 84 35 2010-08-25 # Or use the function cbind() to combine data frames along columns: Start_date <- as.Date(c(“2012-03-01”, “2013-02-13”, “2012-10-10”, “2011-05-10”,“2001-08-25”)) # Use this vector directly: df <- cbind(data_test, Start_date) print(df) ## Name Gender Score Age End_date Start_date ## 1 Piotr Male 80 42 2014-03-01 2012-03-01 ## 2 Pawel Male 88 38 2017-02-13 2013-02-13 ## 3 <NA> Female 92 26 2014-10-10 2012-10-10 ## 4 Lisa Female 89 30 2015-05-10 2011-05-10 ## 5 Laura Female 84 35 2010-08-25 2001-08-25 # or first convert to a data frame: df <- data.frame(“Start_date” = t(Start_date)) df <- cbind(data_test, Start_date) print(df) ## Name Gender Score Age End_date Start_date ## 1 Piotr Male 80 42 2014-03-01 2012-03-01 ## 2 Pawel Male 88 38 2017-02-13 2013-02-13 ## 3 <NA> Female 92 26 2014-10-10 2012-10-10 ## 4 Lisa Female 89 30 2015-05-10 2011-05-10 ## 5 Laura Female 84 35 2010-08-25 2001-08-25