I want to add a new column to the data frame, which is based on row-based calculation. Suppose I have a data frame like this:
x <-as.data.frame(matrix(1:10, 5, 2))
V1 V2
1 1 6
2 2 7
3 3 8
4 4 9
5 5 10
If I want to perform some operation to create a new column, I can use the rowwise () and do () commands to do this. For instance:
y <- rowwise(x) %>% do (foo = .$V1 * .$V2)
I can even add this to an existing data frame as such:
y <- rowwise(x) %>% bind_cols(do (., foo = .$V1 * .$V2))
It all works, but the result is not quite what I want. The values in y $ foo are lists, not numeric.
V1 V2 foo
1 1 6 6
2 2 7 14
3 3 8 24
4 4 9 36
5 5 10 50
It looks right, but it is not.
class(y$foo)
[1] "list"
So, two questions:
- Is there a way to make numeric numbers instead of lists?
- Is there a better way to approach this?
Update:
This is closer to what I'm trying to do. Given this feature:
pts <- 11:20
z <- function(x1, x2) {
min(x1*x2*pts)
}
This does not give the expected result:
y <- x %>% mutate(foo = z(V1, V2))
V1 V2 foo
1 1 6 66
2 2 7 66
3 3 8 66
4 4 9 66
5 5 10 66
:
y <-rowwise(x) %>% bind_cols( do (., data.frame(foo = z(.$V1, .$V2))))
V1 V2 foo
1 1 6 66
2 2 7 154
3 3 8 264
4 4 9 396
5 5 10 550
? ?