Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding columns to a data table

Tags:

I have a data.frame (or a matrix or any other tabular data structure object for that matter):

df = data.frame(field1 = c(1,1,1),field2 = c(2,2,2),field3 = c(3,3,3)) 

And I want to copy part of its columns - given in the vector below:

fields = c("field1","field2") 

to a new data.table that already has 1 or more columns:

dt = data.table(fieldX = c("x","x","x")) 

I'm looking for something more efficient (and elegant) than:

for(f in 1:length(fields)) { dt[,fields[f]] = df[,fields[f]] } 
like image 798
user1701545 Avatar asked Sep 28 '13 21:09

user1701545


People also ask

How do I add a column to a data table?

In the data table structure, click the plus sign between the nodes where you want to add columns, and select Add columns. Tip: You can also add columns between previously added transformation groups for a selected node. Select data to insert columns from. In the flyout, click Settings for added columns.

How do I add a column to a data table in Excel?

To insert a column, pick any cell in the table and right-click. Point to Insert, and pick Table Rows Above to insert a new row, or Table Columns to the Left to insert a new column.

How do you add data to a data table?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.


1 Answers

You can use cbind:

cbind(dt, df[fields]) 

However, the most efficient way is still probably going to be to use data.table's assign by reference:

dt[, (fields) := df[fields]] 
like image 174
Kevin Ushey Avatar answered Nov 04 '22 00:11

Kevin Ushey