Where is my simple loop going wrong?

I have 3 data frames of names and heights - I have put them into a list. The names are common across the data frames, but heights are not.

There are 4 names total. For each name, I want to dump their height into a vector. Then I want to put all those (4 vectors each containing 3 values) into a new list.

I think I'm close, but somehow my for loop is not returning the height values by name. Can you help me correct this? Reprex:

#Make some  fake data with names and heights
mat1 <- data.frame("name"=c("bob", "alice", "mike", "rob"), "height"=c(1,2,3,4))
mat2 <- data.frame("name"=c("bob", "alice", "mike", "rob"), "height"=c(1.5,2.5,3.5,4.5))
mat3 <- data.frame("name"=c("bob", "alice", "mike", "rob"), "height"=c(1.9,2.9,3.9,4.9))

#Store these into a list called obs_mats
obs_mats <- list(mat1, mat2, mat3)

#Make a list of empty vectors 
mynumber <- nrow(mat1) #Tells how many vectors we need (4 people, so 4 vectors)

#A simple loop to actually make the empty vectors
mylist <- list()
for(i in 1:mynumber){
  mylist[[i]] <- vector(mode="numeric")

#Need help here!
#Get the heights of 'Bob' across the 3 data frames, and store those values in the 1st vector of 'mylist'
#Then repeat for Alice
#etc etc
for(i in seq_along(obs_mats)){
  result <- obs_mats[[i]]$height
    mylist[[i]] <- append(mylist[[i]], result) #Store the results into 'mylist'

What I have (first vector aka Bob):

> mylist[[1]]
[1] 1 2 3 4

What I want

> mylist[[1]]
[1] 1 1.5 1.9

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.