Reputation: 359
I am trying to create a loop over variable names in R. It should do the square root of the sum of both variables. I have this up to now:
Variable names are x1,y1, x2,y2, ... x30,y30 (all in one matrix, matrix$x1, matrix$x2)
x1 <- c(2,2,2,3,1,2,4,6,1)
y1 <- c(5,4,3,3,4,2,1,6,3)
x2 <- c(8,2,7,3,1,2,2,2,4)
y2 <- c(1,3,3,3,1,2,4,3,7)
x3 <- c(4,4,1,2,4,6,3,2,3)
y3 <- c(1,2,3,3,1,2,4,6,6)
matrix <- cbind(x1,y1,x2,y3,x3,y3)
for(i in 1:30){
result[[i]] <- sqrt(x`i' + y`i')
}
What can I do?
Upvotes: 0
Views: 342
Reputation: 2470
I'm not sure what the original question looked like but your code now seems fine except that you need to use paste()
to construct the variable names and get()
to get them.
for(i in 1:30){
result[[i]] <- sqrt(get(paste('x',i,sep='')) + get(paste('y',i,sep='')))
}
Upvotes: 1
Reputation: 973
Ok, that format is a little awkward but still managable. We look for the columnnames having the current 'i' in their name and calculate the sqrt of their sums.
result <- vector()
for (i in 1:3){
result[i] <- sqrt(sum(matrix[,which(grepl(i,colnames(matrix)))]))
}
using your data gives:
> result
[1] 7.348469 7.615773 7.549834
Upvotes: 0
Reputation: 4216
Here's an example matrix:
dat <- matrix(1:300, ncol = 60)
colnames(dat) <- paste0(rep(c("x", "y"), 30), rep(1:30, each = 2))
And here's a solution:
for (i in 1:30) {
assign(paste0("result", i), sqrt( dat[, paste0("x", i)] + dat[, paste0("y", i)] ) )
dat <- cbind(dat, get(paste0("result", i)))
}
colnames(dat)[61:90] <- paste0("result", 1:30)
Upvotes: 1