0

I wrote a function that randomly increases the c% percentage of data by i%. I need to do this on multiple dataframes. So the function does that, but I am unable to access the processed value from the outside.

library(tidyverse) value <- iris[1:120,] iris1 <- value[2:95,] set.seed(42) attackfunc <- function(day,dataattack,howmuchattack){ shuffled= day[sample(1:nrow(day)), ] n = as.integer((dataattack/100)*nrow(day)) #select percentage of data to be changed extracted <- shuffled[1:n, ] extracted$changedload <- extracted[,1]*((howmuchattack/100)+1) #how much the data changes pertubeddata<- shuffled %>% mutate(Sepal.Length = ifelse(row_number() <= n, extracted$changedload, Sepal.Length)) reshuffled <- pertubeddata[order(as.numeric(rownames(pertubeddata))),] reshuffled} 

I would like to access reshuffled from outside the function so that I can use that to do some more calculations.

Thank you.

3
  • 1
    You can use <<- instead of <- to modify a variable of the parent scope. If the variable does not exist in the parent scope, it will be created. However, I think it would be best to return(reshuffled) and work with the returned object, to call another function inside your function or to simply append the function. Commented Jul 27, 2022 at 21:38
  • 1
    Can you just put the result into a dataframe? i.e. dat <-attackfunc() Commented Jul 27, 2022 at 21:39
  • Thank you all....all of the ideas worked!! Commented Jul 27, 2022 at 23:11

1 Answer 1

1

set reshuffled as an empty object before your formula, then in your formula change <- to <<- as per

 reshuffled <<- pertubeddata[order(as.numeric(rownames(pertubeddata))),] 

Hope this is useful

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.