R 新手。我想通過幾個 data.frames 運行 SVM 并自動化該程序。我在一個串列中得到了 data.frames,但不知道如何回圈它們以將所有可能的可能性放入我的函式中。簡而言之,我想擺脫代碼末尾的復制和粘貼。此外,有沒有辦法根據 myfunction 的傳入資料標記我的情節?
df1<-iris
df2<-iris
df2$Petal.Width = df2$Petal.Width 2
df3<-iris
df3$Petal.Width = df3$Petal.Width-2
df4<-iris
df4$Petal.Width = df4$Petal.Width-5
Werte <- list(df1,df2,df3,df4)
new_function <- function(V1, V2){
m2<-data.frame(V1$Petal.Width, V2$Petal.Width)
plot(m2)
}
new_function(V1=Werte[[1]],V2=Werte[[2]])
new_function(V1=Werte[[1]],V2=Werte[[3]])
new_function(V1=Werte[[1]],V2=Werte[[4]])
new_function(V1=Werte[[2]],V2=Werte[[3]])
new_function(V1=Werte[[2]],V2=Werte[[4]])
new_function(V1=Werte[[3]],V2=Werte[[4]])
uj5u.com熱心網友回復:
這樣的事情怎么樣:
combs <- combn(length(Werte), 2)
lapply(1:ncol(combs), function(i){
new_function(V1=Werte[[combs[1,i]]],
V2=Werte[[combs[2,i]]])})
uj5u.com熱心網友回復:
一個解決方案combn。函式combn有一個引數FUN,旨在將函式應用于每個組合。
new_function <- function(V1, V2){
m2 <- data.frame(x = V1$Petal.Width, y = V2$Petal.Width)
plot(y ~ x, m2)
}
combn(length(Werte), 2, function(k) {
new_function(Werte[[ k[1] ]], Werte[[ k[2] ]])
}, simplify = FALSE)
uj5u.com熱心網友回復:
創建圖的一種方法是不使用 loop
new_function <- function(data, x1, x2){
V1 <- data[[x1]]
V2 <- data[[x2]]
m2 <- data.frame(V1$Petal.Width, V2$Petal.Width)
plot(m2, main = paste('Plot of dataframe', x1, 'and', x2))
}
Diff_Combs <- combn(1:length(Werte), m = 2)
apply(Diff_Combs, 2, function(x) {
x1 <- x[1]
x2 <- x[2]
y <- new_function(Werte, x1, x2)
return(y)
})
使用 afor loop和if陳述句的其他方式
for(i in 1:length(Werte)) {
for(j in 1:length(Werte)) {
if (i < j) {
plot(Werte[[i]]$Petal.Width, Werte[[j]]$Petal.Width,
main = paste('Plot of dataframe', i, 'and', j))
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375190.html
上一篇:根據另一列更改具有多個值的列
