迭代传递的组合 - R

时间:2018-02-08 04:22:37

标签: r loops iteration

无法创建循环来处理传递的不同输入组合。以下是一个非功能性的例子,

funcOne <- function(input){
  test <- data.frame(c = input, d = c(1:2))
  return(test)
}

funcTwo <- function(input2, input2.2){
  testing <- data.frame(a = input2, b = c(6:7))

  testing$why <- ifelse(input2.2 == 0, testing$why <- c(1:2), testing$why <- c(3:4))
  return(testing)
}

input1 <- c("ten", "four")
input2 <- c("sara", "john")
input2.2 <- c(0:1)
comboOne <- 0 
comboTwo <- 0
combinations <- 0

for(i in 1:2){
  comboOne[i] <- funcOne(input1[i])
  comboTwo[i] <- funcTwo(input2[i], input2.2[i])

  print(combinations[[i]] <- list(comboOne, comboTwo))
}

我知道上面的循环不起作用,但因此我无法理解。这就是我手头的数据。

此外,另外一个问题,从我的理解 - 1将通过i传递给一个数据帧,然后将传递2以提供第二个数据帧。

但如果我需要组合怎么办?例如,对于comboTwo,我想为两个输入传递“1,1”,我想传递“1,2”“2,1”,“2,2”以获得由func生成的数据帧的所有组合。功能。

2 个答案:

答案 0 :(得分:1)

我会在循环外创建一个组合数据框,并在行索引上循环:

combs <- expand.grid(input1,input2,stringsAsFactors = FALSE)
combs 

Var1 Var2
1  ten sara
2 four sara
3  ten john
4 four john

for (i in 1 :nrow(combs)){
    cat(combs[[i,1]]," ",combs[[i,2]],"\n")
}

ten   sara 
four   sara 
ten   john 
four   john 

我试图理解你想要做什么,你失败的原因是你无法将数据帧分配给矢量。您必须将comboOnecomboTwocombinations初始化为列表。

comboOne <- list() 
comboTwo <- list()
combinations <- list()

combs <- expand.grid(input1,input2,input2.2,stringsAsFactors = FALSE)
combs 
Var1 Var2 Var3
1  ten sara    0
2 four sara    0
3  ten john    0
4 four john    0
5  ten sara    1
6 four sara    1
7  ten john    1
8 four john    1

此外,您需要将[]更改为[[]]

for(i in 1 :nrow(combs)){
    dataframe1 <- funcOne(combs[i,"Var1"])
    dataframe2 <- funcTwo(combs[i,"Var2"],combs[i,"Var3"])
    combinations[[i]] <- list(dataframe1,dataframe2)
}

结果:

combinations[1]
[[1]]
[[1]][[1]]
c d
1 ten 1
2 ten 2

[[1]][[2]]
a b why
1 sara 6   1
2 sara 7   1

答案 1 :(得分:0)

根据您的要求,这是带有功能的代码。它有效,有警告。

funcOne <- function(input){
    test <- data.frame(c = input, d = c(1:2))
    return(test)
  }

  funcTwo <- function(input2, input2.2){
    testing <- data.frame(a = input2, b = c(6:7))

    testing$why <- ifelse(input2.2 == 0, testing$why <- c(1:2), testing$why <- c(3:4))
    return(testing)
  }

  input1 <- c("ten", "four")
  input2 <- c("sara", "john")
  input2.2 <- c(0:1)
  comboOne <- 0 
  comboTwo <- 0
  combinations <- 0

  for(i in 1:2){
    comboOne <- funcOne(input1[i])
    comboTwo <- funcTwo(input2[i], input2.2[i])

    print(combinations<- list(comboOne, comboTwo))
  }

结果:

  [[1]]
  c d
  1 ten 1
  2 ten 2

  [[2]]
  a b why
  1 sara 6   1
  2 sara 7   1

  [[1]]
  c d
  1 four 1
  2 four 2

  [[2]]
  a b why
  1 john 6   3
  2 john 7   3