How do I create a new data frame based on a table I generated by R? -
How do I create a new data frame based on a table I generated by R? -
i csv file thousands of rows , few columns. please see next illustration of file like:
subject duration 1.3 b 6.7 c 3.2 2.5 d 2.7 e 99 f 8.4 g 12.5 h 19.7 z 3.2 56 b 9.4 . . . . . .
please notice same subject, duration might vary. want add together duration each particular subject, example, want know total duration subject a, total duration subject b, etc. have many subject titles cannot manually type every single subject , inquire answer. want find out sum of duration each subject, , create new info frame or new file have subject name corresponding total duration.
thank much in advance!!!!!!
here's base of operations version might work. borrowed illustration karsten.
what split data.frame
according subject
. results in list
split(d, d$subject) $a subject duration 1 1.3 4 2.5 11 56.0 $b subject duration 2 b 6.7 12 b 9.4 $c subject duration 3 c 3.2
using lapply
, flip through each list element , sum column duration
. added na.rm = true
function still sums if nas present.
i nowadays in 1 line
lapply(split(d, d$subject), function(x) sum(x$duration, na.rm = true)) $a [1] 59.8 $b [1] 16.1 $c [1] 3.2
you can unlist
or set result in data.frame
transform list more compact.
unlist(lapply(split(d, d$subject), function(x) sum(x$duration, na.rm = true))) b c d e f g h z 59.8 16.1 3.2 2.7 99.0 8.4 12.5 19.7 3.2
r
Comments
Post a Comment