我想以 R 風格(lapply?)撰寫一個 for 回圈以避免以下重復代碼。
df1$fusion <- apply(df1[, cols], 1, paste, collapse = "-" )
df2$fusion <- apply(df2[, cols], 1, paste, collapse = "-" )
df3$fusion <- apply(df3[, cols], 1, paste, collapse = "-" )
df4$fusion <- apply(df4[, cols], 1, paste, collapse = "-" )
df5$fusion <- apply(df5[, cols], 1, paste, collapse = "-" )
df6$fusion <- apply(df6[, cols], 1, paste, collapse = "-" )
df7$fusion <- apply(df7[, cols], 1, paste, collapse = "-" )
df8$fusion <- apply(df8[, cols], 1, paste, collapse = "-" )
df9$fusion <- apply(df9[, cols], 1, paste, collapse = "-" )
df10$fusion <- apply(df10[, cols], 1, paste, collapse = "-" )
df11$fusion <- apply(df11[, cols], 1, paste, collapse = "-" )
df12$fusion <- apply(df12[, cols], 1, paste, collapse = "-" )
我該怎么做?像shell腳本風格的東西?
df_ls=("df1 df2 df3 df4 df5 df6 df7 df8 df9 df10 df11 df12")
for i in $df_ls
do
${i}$fusion <- apply(${i}[, cols], 1, paste, collapse = "-" )
done
uj5u.com熱心網友回復:
帶清單。例如在你的情況下。
list_df_general <- list(df, df2,...,df12) # load your date frames
lista_new <- list() # list empty
for(i in 12){
lista_new[[i]] <- apply(lista_df_general[[i]][, cols], 1, paste, collapse = "-" )
}
對于串列中的瀏覽器,您應該這樣做
list_new[[1]] or list_new[[2]] with 3,4,...,12.
uj5u.com熱心網友回復:
你可以使用類似的東西
my_Fun <- function(df, cols)
{
df$fusion <- apply(df[, cols], 1, paste, collapse = "-" )
}
for(i in 1 : 12)
{
variable_Name <- paste0("df", i)
assign(x = variable_Name, value = my_Fun(df = get(x = variable_Name), cols = cols))
}
uj5u.com熱心網友回復:
您可以在資料框串列上使用lapply
和的組合。apply
這將回傳一個資料框串列。
df_ls <- mget(paste0("df", 1:12))
lapply(df_ls, function(x) {x$fusion <- apply(x[, cols], 1, paste, collapse = "-" ); x})
uj5u.com熱心網友回復:
串列中的多個資料框總是更方便,在 中找到它們.GlobalEnv
并使用mget
. 現在我們可以使用lapply
將任何函式應用于此串列;我們將定義一個匿名function
用戶,它Reduce
可以方便地paste0
為我們完成行和列的回圈作業,而且速度很快。
df_lst <- mget(paste0('df', 1:n)) ## put DFs in list
cols <- paste0('X', 2:5) ## define columns, say 2 to 5
res <- lapply(df_lst, function(df) {df$fusion <- Reduce(\(x, y) paste0(x, '-', y), df[cols]); df})
res
# $df1
# X1 X2 X3 X4 X5 fusion
# 1 A A T G C A-T-G-C
# 2 A T T C G T-T-C-G
# 3 A G A G A G-A-G-A
#
# $df2
# X1 X2 X3 X4 X5 fusion
# 1 A T C C C T-C-C-C
# 2 T T A G A T-A-G-A
# 3 G C A A A C-A-A-A
#
# $df3
# X1 X2 X3 X4 X5 fusion
# 1 G G A T T G-A-T-T
# 2 T C T C T C-T-C-T
# 3 G T G C G T-G-C-G
#
# $df4
# X1 X2 X3 X4 X5 fusion
# 1 G T A G G T-A-G-G
# 2 G A G T C A-G-T-C
# 3 T G T C A G-T-C-A
如果由于某種原因,您需要之后.GlobalEnv
可能使用的資料框list2env(res, .GlobalEnv)
(類似于我對下面的示例資料所做的)。
資料:
set.seed(42)
n <- 4
replicate(n, data.frame(matrix(sample(LETTERS[c(1, 20, 3, 7)], 15, replace=TRUE), 3, 5)), simplify=FALSE) |>
setNames(paste0('df', seq_len(n))) |> list2env(.GlobalEnv)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/497349.html
標籤:r
下一篇:新列取決于其余R的值