Applying a function for each value in a row to all values in another row, append results

StackOverflow https://stackoverflow.com/questions/18316374

Вопрос

I have read many related posts, but can't seem to find an solution to what seems like it should be a very simple problem. I'm using R and I want to apply the following equation x = R+2B to my data frame. I have a row R which is a vector of values 1:6, and a row B which is the same. I want to create a new vector that is the values of R[i]+2B[1:6]. So for each R value there will be 6 resulting values. In total I will have 36 values in the vector.

> data
  R B
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6

> x <- matrix(ncol=6,nrow=6)
> for (i in nrow(data)){ 
+   x[i] = data$R[i]+(2*data[1:6,2])
 + }
Warning message:
In x[i] = data$R[i] + (2 * data[1:6, 2]) :
number of items to replace is not a multiple of replacement length

Here is what I'm trying, which isn't right. Any thoughts on how to do this simply and efficiently?

Thank you in advance.

Это было полезно?

Решение

You can use sapply:

sapply(data$R, function(x)x + 2*data[1:6,"B"])

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    4    5    6    7    8
[2,]    5    6    7    8    9   10
[3,]    7    8    9   10   11   12
[4,]    9   10   11   12   13   14
[5,]   11   12   13   14   15   16
[6,]   13   14   15   16   17   18

If you want a vector instead of a matrix, you can use as.vector

Другие советы

You're looking for expand.grid:

data <- data.frame(R=1:6,B=1:6)
out <- expand.grid(data$R,2*data$B)
apply(out,1,sum)
 [1]  3  4  5  6  7  8  5  6  7  8  9 10  7  8  9 10 11 12  9 10 11 12 13 14 11
[26] 12 13 14 15 16 13 14 15 16 17 18
sapply(data[, 'R'], function(x)x + 2*data[, 'B'])

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    4    5    6    7    8
[2,]    5    6    7    8    9   10
[3,]    7    8    9   10   11   12
[4,]    9   10   11   12   13   14
[5,]   11   12   13   14   15   16
[6,]   13   14   15   16   17   18

Each column corresponds to a row of 'R'.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top