I created a list containing two data lists (character array region and a list results) of the same length. (I tried to manage the data in data.frame, but it seems to be complicated to add data to a data.frame).
study = list(
region = character(),
results = list()
)
study$region[1] = "Hamburg"
study$results[[1]] = data.frame(month=c(1:5), maxTemp=c(-12, -1, 3, 10, 23))
study$region[2] = "Bremen"
study$results[[2]] = data.frame(month=c(1:5), maxTemp=c(-9, -1, 6, 10, 21))
str(study)
print("Maximum temperature of all study regions:")
max(study$results[[1:2]]$maxTemp)
I want to find out the maximum temperature of all timepoint of all regions. I can address each region after another by using e.g. max(study$results[[1]]$maxTemp, but when I try to address all regions max(study$results[[1:2]]$maxTemp I receive an error:
Error in study$results[[1:2]]$maxTemp :
$ operator is invalid for atomic vectors
Where is my mistake? How can I address fields of a several data.frames that are saved in a list of a list? And what are atomic vectors?
[[can only return a single element. I thought[[would have thrown an error because of that, not the error you are seeing, but reading?"["tells what R does with a call such as yours and explains the behaviour (from?"["):The reason for your error is this:
which indicates that R really did this
i.e. return the second component (column) of the first data frame, which is an atomic vector because R drops the empty dimension.
$can not be used on atomic vectors hence the error.If you want to iterate over the list that is
study$results,lapply()orsapply()are your friends:If you popped names on the components in
$resultsyou’d get them in the output too:which is easier to use and then you don’t need the
$regioncomponent if you wish.