1

I have 90 variables:

x111 <- 23
x112 <- 54
...
x1130 <- 69

x2111 <- 149
x2112 <- 12
...
x2130 <- 45

x3111 <- 85
x3112 <- 105
...
x3130 <- 501

I need to calculate a sum of squares of each variable (SS), for example, x111^2 + x112^2 + ...+ x3130^2

The function I have is:

SSobs_calculator <- function(obs) {
obs_value <- (obs)^2
total_obs_value = total_obs_value + obs_value
return(obs_value)
}

The problem is I do not know how to pass variables. In the following code:

for(i in 1:90){
   SSobs_calculator(paste0("x1_11",i)
 }

would not work, because I can't pass variables that start with x1_2.. and x1_3... Also the index for each group goes to 30, and 90 will not be valid.

Should I join all variables into a data frame, and then square it? Is there any other solution?

1 Answer 1

3

We can get the values of the objects in a list with mget, then take the power and Reduce to a single number by taking the sum (+) of the list elements

Reduce(`+`, lapply(mget(ls(pattern = '^x\\d+$')), `^`, 2))

Or after getting the elements in a list, unlist and then do the ^ in a single step

sum(unlist(mget(ls(pattern = '^x\\d+$')))^2)

data

x111 <- 23
x112 <- 54
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting all elements in a list and squared, but when I am trying to sum up, I get an error: 'Error in sum(unlist(+, SSobs1l)) : invalid 'type' (builtin) of argument'
@FeyziBagirov It is based on the assumption that all the objects in the global env followed by the pattern 'x' followed by some numbers. Suppose you have some objects named as x242 <- 'A', then it would also be in the list and it is a character class. Please check if you have any objects like that in the global env

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.