Insert a Row in a Data.Table

Insert a new row into DataTable

// get the data table
DataTable dt = ...;

// generate the data you want to insert
DataRow toInsert = dt.NewRow();

// insert in the desired place
dt.Rows.InsertAt(toInsert, index);

Insert a row in a data.table

To expand on @Franks answer, if in your particular case you are appending a row, it's :

set.seed(12345) 
dt1 <- data.table(a=rnorm(5), b=rnorm(5))

The following are equivalent; I find the first easier to read but the second faster:

microbenchmark(
rbind(dt1, list(5, 6)),
rbindlist(list(dt1, list(5, 6)))
)

As we can see:

                             expr     min      lq  median       uq     max
rbind(dt1, list(5, 6)) 160.516 166.058 175.089 185.1470 457.735
rbindlist(list(dt1, list(5, 6))) 130.137 134.037 140.605 149.6365 184.326

If you want to insert the row elsewhere, the following will work, but it's not pretty:

rbindlist(list(dt1[1:3, ], list(5, 6), dt1[4:5, ]))

or even

rbindlist(list(dt1[1:3, ], as.list(c(5, 6)), dt1[4:5, ]))

giving:

            a          b
1: 0.5855288 -1.8179560
2: 0.7094660 0.6300986
3: -0.1093033 -0.2761841
4: 5.0000000 6.0000000
5: -0.4534972 -0.2841597
6: 0.6058875 -0.9193220

If you are modifying a row in place (which is the preferred approach), you will need to define the size of the data.table in advance i.e.

dt1 <- data.table(a=rnorm(6), b=rnorm(6))
set(dt1, i=6L, j="a", value=5) # refer to column by name
set(dt1, i=6L, j=2L, value=6) # refer to column by number

Thanks @Boxuan, I have modified this answer to take account of your suggestion, which is a little faster and easier to read.

Insert a row from one DataTable in the middle of another DataTable

You can clone the source row's items and then create a DataRow using them:

var sourceItems = (object[])(table2.Rows[0].ItemArray.Clone());

DataRow targetRow = table1.NewRow();
targetRow.ItemArray = sourceItems;
table1.Rows.InsertAt(targetRow, index);

(note that it's not clear in your question which datatable is the source and which is the target, I assumed table2 is the source and table1 the target)

how to insert sequential rows in data.table in R (Example given)?

Here's an approach that creates the target and then uses a join to add in the visits information. The ifelse statement just helps up clean up the NA from the merge. You could also leave them in and replace them with := in the new data.table.

target <- data.table(
customer = rep(unique(df$customer), each = 24),
hour = 0:23)

df_join <- df[target, on = c("customer", "hour"),
.(customer, hour, visits = ifelse(is.na(visits), 0, visits))
]

all.equal(df_expected, df_join)

Edit:

This addresses the request to include the location_id column. One way to do this is with by=location in the creation of the target. I've also added in some of the code from chinsoon12's answer.

target <- df[ , .("customer" = rep(unique(customer), each = 24L),
"hour" = rep(0L:23L, times = uniqueN(customer))),
by = location_id]

df_join <- df[target, on = .NATURAL,
.(customer, location_id, hour, visits = fcoalesce(visits, 0))]

all.equal(df_expected, df_join)

Insert datarow from one datatable to a particular index

try with Clone

dr= dt1.NewRow();
dr.ItemArray = targetTable.Rows[0].ItemArray.Clone() as object[];
dt1.Rows.InsertAt(dr, index);

How to insert row at any desired position in datatable?

Try this. I think the error you are getting is bcz you are not creating NewRow.

    DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));

DataRow dr;
dr = dt.NewRow();
dr[0] = "A";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr[0] = "C";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr[0] = "B";
dt.Rows.InsertAt(dr,1);

foreach (DataRow d in dt.Rows)
{
Console.WriteLine(d[0].ToString());

}

Console.Read();

How to insert a Data Row in the first line in a DataTable?

In general, the approach you are using should work as expected. Nevertheless, if you are populating your DataCells with TextFields, in that case you will have to add a GlobalKey to each TextField, so that Flutter knows where each DataCell belongs.

For more info on Keys watch this Flutter mini-tutorial.

Please try the following complete running sample

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

@override
Widget build(BuildContext context) {
return Tabelle();
}
}

class Tabelle extends StatefulWidget {
@override
_TabelleState createState() => _TabelleState();
}

class _TabelleState extends State<Tabelle> {

List<DataRow> _rowList = [
DataRow(
cells: <DataCell>[
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
]),
];

void _addRow() {
setState(() {
_rowList.insert(0, (DataRow(
cells: <DataCell>[
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
DataCell(TextField(key: GlobalKey(),)),
])));
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Plan'), actions: [
TextButton(
onPressed: _addRow,
child: Text(
'Neues Training',
style: TextStyle(color: Colors.white),
),
),
]),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
dataRowHeight: 200,
headingRowColor:
MaterialStateColor.resolveWith((states) => Colors.black26),
dataRowColor:
MaterialStateColor.resolveWith((states) => Colors.black26),
columnSpacing: 20,
columns: [
DataColumn(label: Text('seconds', style: TextStyle(fontSize: 16),)),
DataColumn(label: Text('Datum', style: TextStyle(fontSize: 16),)),
DataColumn(label: Text('Datum', style: TextStyle(fontSize: 16),)),
DataColumn(label: Text('Datum', style: TextStyle(fontSize: 16),)),
], rows: _rowList),
)),
);
}
}

Adding new row to datatable's top

You use the NewRow to create a row with the same columns. To actually get it into the DataTable, you've got to do

myDataTable.Rows.InsertAt(myDataRow, 0);

Where 0 is the index you want to insert it at.



Related Topics



Leave a reply



Submit