Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

How to prevent function in R from updating values based on last variable specified?

I have the following function:

stats <- function(data) {
   maxDay <<- max(data$TotalGB)
   avgDay <<- mean(data$TotalGB)
   P95Day <<- quantile(data$TotalGB, probs = (.95))
   
   return(list(paste0("The max number of GBs for is: ", maxDay), paste0("The average number of GBs is: ", avgDay), 
   paste0("The 95P GBs is: ", P95Day)))
}

This function returns the following results:

[[1]] [1] "The max number of GBs for is: 700"

[[2]] [1] "The average number of GBs is: 350"

[[3]] [1] "The 95P GBs is: 655"

Now if I want to obtain these stats for more than 1 user, I am doing the following

user1 <- stats(df_1)
user2 <- stats(df_2)

When I do this, the value for maxDay, avgDay and P95Day will reflect the stats from user 2. What can I add so that instead of overriding the results, I could obtain the unique stats for each user.

I was thinking of just doing something like user1$avgDay but this returns in NULL


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why not something like the following? Instead of returning strings with the stats you want paste'd on a description, use the descriptions as list names and return a named list.

stats <- function(data) {
  maxDay <- max(data$TotalGB)
  avgDay <- mean(data$TotalGB)
  P95Day <- quantile(data$TotalGB, probs = 0.95)
  
  list(maxDay = maxDay, avgDay = avgDay, P95Day = P95Day)
}

user1 <- stats(df_1)
user2 <- stats(df_2)

And there is no need to set three global variables. Example access:

user1$avgDay
user2$P95Day

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...