WsnCode
WsnCode

Reputation: 49

Filling dataframe with loops

I have a dataframe:

Start <- data.frame("Number" = 2,"Square" = 4,"Cube" = 8)

A Vector of inputs:

Numbers <- c(3,5)

I want to iterate the elements of Numbers in the function Squarecube and fill the dataframe with the results:

 SquareCube <- function(x){ df <- c(x^2,x^3) 
df}

Desired Output:

 Filled <- data.frame("Number" = c(2,3,5),"Square" = c(4,9,25),"Cube" = c(8,27,125))

Note: Already searched for this topic , but in this case the size of the vector Numbers can be different. My intent is to fill the dataframe with the results of the function.

Thanks

Upvotes: 0

Views: 71

Answers (2)

younggeun
younggeun

Reputation: 953

outer() function produces matrix which has exactly same output of yours. You can just change it to data frame and rename.

(Filled <- outer(
  c(2, 3, 5),
  1:3,
  FUN = "^"
))

#>      [,1] [,2] [,3]
#> [1,]    2    4    8
#> [2,]    3    9   27
#> [3,]    5   25  125

For this matrix, you can use any function what you know to

  1. change class
  2. change column names

Here, for instance, dplyr::rename():

library(tidyverse)

Filled %>%
  as_tibble() %>% # make data frame
  rename(Number = V1, Square = V2, Cube = V3) # rename column names

#> # A tibble: 3 x 3
#>   Number Square  Cube
#>    <dbl>  <dbl> <dbl>
#> 1      2      4     8
#> 2      3      9    27
#> 3      5     25   125

Upvotes: 1

mysteRious
mysteRious

Reputation: 4294

If I am reading your question right, you may just be having issues with structure that do.call may be able to help with. I also redefined the function slightly to accommodate the naming:

Start <- data.frame("Number" = 2,"Square" = 4, "Cube" = 8)
Number <- c(3,5)

Define your function:

SquareCube <- function(x){ list(Number=x,Square=x^2,Cube=x^3) } 

Then construct the data frame with desired end results:

> rbind(Start, data.frame(  do.call(cbind, SquareCube(Number))  ))
  Number Square Cube
1      2      4    8
2      3      9   27
3      5     25  125

You can also make a wrapper function and just hand it the Start data and the original Number list that you want to process, which will yield a data frame:

> makeResults <- function(a, b) { rbind(a, data.frame(do.call(cbind,SquareCube(b)))) }
> makeResults(Start, Number)
  Number Square Cube
1      2      4    8
2      3      9   27
3      5     25  125

Upvotes: 1

Related Questions