Home > Net >  Change an entry in a vector to reach a target value of a function in R
Change an entry in a vector to reach a target value of a function in R

Time:05-09

I have the following data:

z <- c(3,4,22,1,323,42,4,04,99,9,24,76,1)
target_mean <- 55

My question is: what value of z[1] (first entry in z) gets me my target mean? The answer is 106 (I checked it by manually changing z[1]).

CodePudding user response:

Another option that will be faster for long z:

target_mean * length(z) - sum(z[-1]) 
# [1] 106

Input

z <- c(3,4,22,1,323,42,4,04,99,9,24,76,1)
target_mean <- 55

CodePudding user response:

I solved it. Pretty simple stuff.

for (i in 1:150){
  z[1] = i
  if(mean(z) == 55){
    print(i)
  }
}
  •  Tags:  
  • r
  • Related