e <<- data.env ## here i am storing my rdata
data_frames <- Filter(function(x) is.data.frame(get(x)), ls(envir = e)) ## getting only dataframe
for(i in data_frames) e[[i]] <<- mytest_function(e[[i]]) ### here i am iterating the dataframe
現在,如何將 for 回圈轉換為應用函式?回圈需要很長時間才能迭代。
uj5u.com熱心網友回復:
好的,這里有一些基本的演示,我認為使用 apply 是一個很好的呼叫,特別是因為回圈等環境問題。
# lets create some data.frames
df1 <- data.frame(x = LETTERS[1:3], y = rep(1:3))
df2 <- data.frame(x = LETTERS[4:6], y = rep(4:6))
# what df's are we going to "loop" over
data_frames <- c("df1", "df2")
# just some simple function to paste x and y from your df's to a new column z
mytest_function <- function(x) {
df <- get(x)
df$z <- paste(df$x, df$y)
df
}
# apply over your df's and call your function for every df
e <- lapply(data_frames, mytest_function)
# note that e will be a list with data.frames
e
[[1]]
x y z
1 A 1 A 1
2 B 2 B 2
3 C 3 C 3
[[2]]
x y z
1 D 4 D 4
2 E 5 E 5
3 F 6 F 6
# most of the time you want them combined
e <- do.call(rbind, e)
e
x y z
1 A 1 A 1
2 B 2 B 2
3 C 3 C 3
4 D 4 D 4
5 E 5 E 5
6 F 6 F 6
uj5u.com熱心網友回復:
目前還不清楚你想要的結果是什么。但是,如果您只想將函式應用于資料框中的每一列,那么您只需使用sapply.
sapply(df, function(x) mytest_function(x))
或者你可以使用這個purrr包。
purrr::map(df, function(x) mytest_function(x)) %>%
as.data.frame
如果您有一個資料框串列并且正在對每個資料框應用一個函式,那么您也可以使用purrr.
library(purrr)
purrr::map(data_frames, mytest_function)
uj5u.com熱心網友回復:
當您想將回圈轉換為應用函式時,我通常會使用 lapply 但這取決于具體情況:
my_f <- function(x) {
mytest_function(e[[x]])
}
my_var <- lapply(1:length(data_frames), my_f)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383701.html
