Provisional.Modulation Provisional.Modulation - 2 months ago 6
R Question

R - Call a specific column from every dataframe from list of dataframes

I like to report a specific column from every dataframe from a list of dataframes. Any ideas? This is my code:

# Create dissimilarity matrix
df.diss<-dist(t(df[,6:11]))

mds.table<-list() # empty list of values
for(i in 1:6){ # For Loop to iterate over a command in a function
a<-mds(pk.diss,ndim=i, type="ratio", verbose=TRUE,itmax=1000)
mds.table[[i]]<-a # Store output in empty list
}


Now here is where I'm having trouble. After storing the values, I'm unable to call a specific column from every dataframe from the list.

# This function should call every $stress column from each data frame.
lapply(mds.table, function(x){
mds.table[[x]]$stress
})


Thanks again!

Answer

you are very close:

set.seed(1)
l_df <- lapply(1:5, function(x){
  data.frame(a = sample(1:5,5), b = sample(1:5,5))
})

lapply(l_df, function(x){
  x[['a']]
})

[[1]]
[1] 2 5 4 3 1

[[2]]
[1] 2 1 3 4 5

[[3]]
[1] 5 1 2 4 3

[[4]]
[1] 3 5 2 1 4

[[5]]
[1] 5 3 4 2 1