Matt Gossett
Matt Gossett

Reputation: 184

R For Loop Append Dataframe Iterations to Empty Matrix

I am trying to create an empty matrix and fill it with iterations of a dataframe. Using the below code:

df <- data.frame(col1 = c(1:10), col2 = letters[1:10])
var <- seq(-.25,.25,.05)
var <- var[var != 0]

output <- matrix(ncol=ncol(df)+1, nrow=nrow(df)*length(var))

for(i in 1:length(var)){
  output[i,] <- df %>% mutate(var = df$col1*var[i])
}

With this code, I receive the following error message: incorrect number of subscripts on matrix

Does anyone know what the issue could be? My desired output is for each value in col1 of df to be multiplied times each value in list var.

Thank you for suggestions!

Upvotes: 0

Views: 249

Answers (2)

SteveM
SteveM

Reputation: 2301

To create the 100 row data frame of col1, col2, var

var <- sapply(var, function(x) x * col1)
var <- as.vector(var)
col1 <- rep(col1, 10)
col2 <- rep(letters[1:10], 10)
df <- data.frame(col1, col2, var)
df
    col1 col2   var
1      1    a -0.25
2      2    b -0.50
3      3    c -0.75
4      4    d -1.00
5      5    e -1.25
6      6    f -1.50
7      7    g -1.75
8      8    h -2.00
9      9    i -2.25
10    10    j -2.50

Upvotes: 0

Andrew Brown
Andrew Brown

Reputation: 1065

Not a for-loop, but is this what you wanted for output?

library(dplyr,warn.conflicts = FALSE)

df <- data.frame(col1 = c(1:10), col2 = letters[1:10])
var <- seq(-.25,.25,.05)
var <- var[var != 0]

output <- matrix(ncol=ncol(df)+1, nrow=nrow(df)*length(var))

lapply(1:length(var), function(i) {
  x <- df %>% 
    rowwise() %>% 
    mutate(var = col1*var[i]) %>%
    bind_rows()
}) %>% bind_rows()
#> # A tibble: 100 x 3
#> # Rowwise: 
#>     col1 col2    var
#>    <int> <chr> <dbl>
#>  1     1 a     -0.25
#>  2     2 b     -0.5 
#>  3     3 c     -0.75
#>  4     4 d     -1   
#>  5     5 e     -1.25
#>  6     6 f     -1.5 
#>  7     7 g     -1.75
#>  8     8 h     -2   
#>  9     9 i     -2.25
#> 10    10 j     -2.5 
#> # ... with 90 more rows

Created on 2020-12-03 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions