r - Understanding list behaviour -
i feel have understanding of data.frames , how work, aspects of lists confusing me.
here reproducible data start:
list_a <- structure(list(`one` = structure(list( words = c("a", "b","c", "d", "e", "f")), .names = "words", class = "data.frame", row.names = c(na,-6l)), `two` = structure(list(words = c("a","s","t","z")), .names = "words", class = "data.frame", row.names = c(na, -4l))), .names = c("one", "two"))
this gives us:
list_a $one words 1 2 b 3 c 4 d 5 e 6 f $two words 1 2 s 3 t 4 z
now want loop through list return of results in data.frames.
list <- list() for(i in list_a){list <- append(list, list_a$i$words)}
this produces no results in list. neither does:
for(i in list_a){list <- append(list, list_a[[i]]$words)} error in list_a[[i]] : invalid subscript type 'list'
i thought perhaps reason first loop didn't work was using list_a$i$words
without defining correct names. tried:
for(i in names(list_a)){list <- append(list, list_a$i$words)}
this still gives me list of length 0.
so not understand why attempts tried didnt give results expected, not know why using subscripts gave me error , figured out correct syntax:
for(i in list_a){list2 <- append(list2, i$words)}
however not know why works when using names method did not?
the arguments for
expression in r consists of:
- lhs, iterator take each value of rhs
in
, language keyword- rhs, vector, length of defines number of iterations occur.
when set first loop, rhs length 2 vector of type "list". on lhs have i
1 column data frame. asked $
extract "i" list_a, evaluated null
. in second loop, rhs length 2 vector of type "character". same thing occurred.
$
not evaluate index. use [[
instead , answer expect in second loop.
# initialize list <- list() # loop (i in names(list_a)) { list <- append(list, list_a[[i]]$words) } list # [[1]] # [1] "a" # # [[2]] # [1] "b" # ...
as mentioned roland, appending expensive in r, each iteration creates new copy of object. here 1 alternative try:
# create data frame using of list_a, # coerce character vector # coerce list as.list(unname(unlist(do.call(what = "rbind", args = list_a))))
note "data.frame" objects "list" objects "data.frame" class attribute applied. see same behaviour when working data.frames , $
unevaluated names lists. try this:
# print mtcars data.frame mtcars # set class attribute null class(mtcars) <- null # mtcars list :-) mtcars
edit: $
, [[
operators, means functions can used in special way. can use them normal functions too, passing arguments in round brackets.
# $ function `$`(list_a, "one") # words # 1 # 2 b # ...
the behaviour of these functions different. [[
expects object interprets. $
expects element name tries find.
i <- "one" # $ function, there no element "i" `$`(list_a, i) # null # [[ function, , element "one" present `[[`(list_a, i) # words # 1 # 2 b # ...
Comments
Post a Comment