R: collect the i-th or last rows of each data frame in a list of data frames

This post demonstrates selecting either the last row or the i-th row from each data frame in a list of data frames in R.



the i-th or last rows of data frames within a list



In the following R code, the function collect_ith_or_last_rows() provides a convenient method for selecting either the i-th or last rows of data frames within a list.

# list of data.frames or matrices
list_df_coef <- list(
    L = matrix(c(
        -0.857-0.806-0.731-0.645,
        -0.260-0.265-0.262-0.253,
        -0.407-0.413-0.408-0.395), 
        ncol = 4, byrow = TRUE),
    S = matrix(c(
        0.0010.0020.0030.004,
        0.7710.7720.7730.774,
        -0.015-0.025-0.035-0.045), 
        ncol = 4, byrow = TRUE),
    C = matrix(c(
        -0.181-0.178-0.175-0.172,
        0.0450.0450.0450.045,
        0.0000.0010.0010.001), 
        ncol = 4, byrow = TRUE)
)
 
list_df_coef
 
#---------------------------------------------------------------
# When ith_row = i, it selects the ith rows.
# When ith_row is NULL, it defaults to selecting the last rows.
#---------------------------------------------------------------
collect_ith_or_last_rows <- function(df_list, ith_row = NULL) {
    # Function to get ith or last row of each data frame
    if (is.null(ith_row)) {
        get_selected_rows <- function(df) {tail(df, n = 1)}
    } else {
        get_selected_rows <- function(df) {df[ith_row,,drop=FALSE]}
    }
    # Apply the function to each data frame in the list
    selected_rows <- lapply(df_list, get_selected_rows)
    # Combine the selected rows into one data frame
    combined_df <- do.call(rbind, selected_rows)
    # Set row names based on the names of list ingredients
    rownames(combined_df) <- names(df_list)
    return(combined_df)
}
 
collect_ith_or_last_rows(list_df_coef, 1)
collect_ith_or_last_rows(list_df_coef)
 
cs


The selected results are as follows:

> 
> list_df_coef
$L
       [,1]   [,2]   [,3]   [,4]
[1,] -0.857 -0.806 -0.731 -0.645
[2,] -0.260 -0.265 -0.262 -0.253
[3,] -0.407 -0.413 -0.408 -0.395
 
$S
       [,1]   [,2]   [,3]   [,4]
[1,]  0.001  0.002  0.003  0.004
[2,]  0.771  0.772  0.773  0.774
[3,] -0.015 -0.025 -0.035 -0.045
 
$C
       [,1]   [,2]   [,3]   [,4]
[1,] -0.181 -0.178 -0.175 -0.172
[2,]  0.045  0.045  0.045  0.045
[3,]  0.000  0.001  0.001  0.001
 
> collect_ith_or_last_rows(list_df_coef, 1)
    [,1]   [,2]   [,3]   [,4]
-0.857 -0.806 -0.731 -0.645
S  0.001  0.002  0.003  0.004
-0.181 -0.178 -0.175 -0.172
 
> collect_ith_or_last_rows(list_df_coef)
    [,1]   [,2]   [,3]   [,4]
-0.407 -0.413 -0.408 -0.395
-0.015 -0.025 -0.035 -0.045
C  0.000  0.001  0.001  0.001
> 
 
cs



No comments:

Post a Comment