简体   繁体   中英

R: Change order of several dataframes in a list depending on mean of a specific column

have several lists containing multiple dataframes. All dataframes have the same two column names but different lengths.

A simple example would be:

d1 <- data.frame(y1 = c(1:5), y2 = 3)
d2 <- data.frame(y1 = c(6:13), y2 = 1)
d3 <- data.frame(y1 = c(13:21), y2 = 2)
df_list <- list(d3, d1, d2)

Now I´m looking for a solution to calculate the mean of column y1 in each dataframe in the list and then change the order of the dataframes starting with the one that has the lowest mean of column y1 .

So far, I was able to calculate the means with:

lapply(df_list, function(x) mean(x[,1]))

but I can´t figure out how to combine this with order()

df_list <- df_list[order(lapply(df_list, function(x) mean(x[,1])))]

gives me

"Error in order(lapply(df_list, function(x) mean(x[, 1]))) :
unimplemented type 'list' in 'orderVector1'"

Thanks for your help!

您可以使用下面的代码来完成此操作,但这不会更改列表顺序,因为三个数据帧已经按照您指定的顺序进行了排序:

df_list=df_list[order(sapply(df_list,function(x) mean(x$y1)))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM