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]] }
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.
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.
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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With