Reputation: 463
I have a list of data.frames, mrns[[i]]
, and want to create a new variable for each one, mrns[[i]]$avg.hr.prhr
, which is average heart rate per hour.
My code and error:
for (i in 1:310) {
mrns[[i]]$avg.hr.prhr <- aggregate(raw.Hour ~ raw.HR, data=mrns[[i]], mean)
}
Error in `$<-.data.frame`(`*tmp*`, "avg.hr.prhr", value = list(raw.HR = c(46L, :
replacement has 32 rows, data has 93
I tried to use data.table
as well and was getting the same error and I also created an empty variable before running the loop as well with:
for (i in 1:310) {
mrns[[i]]$avg.hr.prhr <- ""
}
I also checked the rows for each variable in a couple of the data.frames and they seem to be the same number of rows.
length(mrns[[1]]$raw.HR)
[1] 93
length(mrns[[1]]$raw.Hour)
[1] 93
Does anyone have any suggestions?
Edit
Tried to use ave instead of aggregate:
for (i in 1:310) {
mrns[[i]]$avg.hr.prhr <- ave(raw.HR ~ raw.Hour , mrns[[i]], FUN=mean)
}
Error in rep(value, length.out = nrows) :
attempt to replicate an object of type 'language'
In addition: Warning messages:
1: In split.default(x, g) :
data length is not a multiple of split variable
2: In split.default(seq_along(x), f, drop = drop, ...) :
data length is not a multiple of split variable
for (i in 1:310) {
mrns[[i]]$avg.hr.prhr <- ave(raw.HR, raw.Hour, mrns[[i]])
}
Error in interaction(...) : object 'raw.Hour' not found
The thing with the is that I know raw.Hour is not an object, it's just a variable name
names(mrns[[i]])
[1] "raw.Number" "raw.Reading_Status" "raw.Month" "raw.Day"
[5] "raw.Year" "raw.Hour" "raw.Minute" "raw.Systolic"
[9] "raw.Diastolic" "raw.MAP" "raw.PP" "raw.HR"
[13] "raw.Event_Code" "raw.Edit_Status" "raw.Diary_Activity" "na.strings"
[17] "raw.facility" "raw.lastname" "raw.firstname" "raw.id"
[21] "raw.hookup" "raw.datetime" "raw.mrn" "unis"
[25] "ar.value" "ar.cat" "baseline.visit" "visit.date.1"
[29] "total.sleep.time" "ID"
Upvotes: 0
Views: 1189
Reputation: 306
What about lapply
and dplyr
?
library(dplyr)
new_list <- lapply(mrns, function(i) {
i %>% group_by(raw.Hour) %>%
mutate(avg.hr.prhr = mean(raw.HR)) %>%
ungroup()
})
Upvotes: 0
Reputation: 463
for (i in 1:310) {
mrns[[i]]$avg.hr.prhr <- with(mrns[[i]], ave(raw.HR, raw.Hour))
}
Thanks to @PierreLafortune.
Upvotes: 2