我有一个数据框列表,对于列表中的每个数据框,我想对行进行求和并将结果存储在该数据框中的新列中。所以,我写了这个函数:
timepoint_scores <- function(df_list) {
for (i in 1:length(df_list)) {
df <- df_list[[i]]
df$total_score <- apply(df, 1, sum)
} #end of for loop
}# end of timepoint_scores function
我知道 df$total_score <- apply(df, 1, sum) works when I do this to an individual data frame, but I don't understand why this is not working as a for loop.
因为您要从列表中删除数据框
df <- df_list[[i]]
,但没有将其放回df_list
。 df
是一个单独的对象,在每次迭代中都会被覆盖。
你可以尝试一下:
timepoint_scores <- function(df_list) {
for (i in 1:length(df_list)) {
df_list[[i]]$total_score <- apply(df, 1, sum)
}
return(df_list)
}
但是,我会使用
lapply
代替 for
循环,使用 rowSums
代替 apply(df, 1, sum)
,可以写成:
timepoint_scores <- function(df_list) {
df_list <- lapply(df_list, \(x) {x$total_score <- rowSums(x);x})
return(df_list)
}