Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...