Reputation: 1
I am now using the package data.table,however,I can barely find the way to compute by rows. for example :
apply(x,1,sum) # suppose x is a data.frame with many columns
Is there anyone who knows how to do this?
Upvotes: 0
Views: 1208
Reputation: 9
You could try using transform(). For example, using a dummy dataset that I have:
> head(data)
sample time.min abs time.sec
1: pur n 0.0008333334 0.4678054 0.05
2: pur n 0.2508333325 0.4661632 15.05
3: pur n 0.5008333325 0.4663149 30.05
4: pur n 0.7508333325 0.4658490 45.05
5: pur n 1.0008333920 0.4671631 60.05
6: pur n 1.2508333920 0.4657932 75.05
Let's say I want to sum the two "time" columns together, and fill a new column with that value. I could use transform() to do that:
> transform(data, time.sum = time.min + time.sec)
sample time.min abs time.sec time.sum
1: pur n 0.0008333334 0.4678054 0.05 0.05083333
2: pur n 0.2508333325 0.4661632 15.05 15.30083328
3: pur n 0.5008333325 0.4663149 30.05 30.55083328
4: pur n 0.7508333325 0.4658490 45.05 45.80083328
5: pur n 1.0008333920 0.4671631 60.05 61.05083691
Upvotes: 0
Reputation: 49448
Do your best to avoid by-row operations, but if you must:
dt[, your.by.row.operation, by = 1:nrow(dt)]
Upvotes: 2