[英]R Loop a function with data.frame from a list
R 的新手。 我想通过几个 data.frames 运行 SVM 并自动化该过程。 我得到了一个列表中的 data.frames,但不知道如何循环它们以将所有可能的可能性放入我的 function。 简而言之,我想摆脱代码末尾的复制和粘贴。 此外,根据 myfunction 的传入数据,有没有办法 label my plot?
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]])
像这样的东西怎么样:
combs <- combn(length(Werte), 2)
lapply(1:ncol(combs), function(i){
new_function(V1=Werte[[combs[1,i]]],
V2=Werte[[combs[2,i]]])})
使用combn
的解决方案。 Function combn
有一个参数FUN
,用于将 function 应用于每个组合。
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)
创建图的一种方法是不使用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)
})
使用for 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))
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.