How to use dplyr to generate a new column based on rollise data?

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

? ?

+4
3

data.frame do:

y <- rowwise(x) %>% bind_cols(do(., data.frame(foo = .$V1 * .$V2)))
y
##   V1 V2 foo
## 1  1  6   6
## 2  2  7  14
## 3  3  8  24
## 4  4  9  36
## 5  5 10  50
y$foo
## [1]  6 14 24 36 50

rowwise mutate, rowwise do. rowwise, .

x %>% rowwise %>% mutate(foo = z(V1, V2))
## Source: local data frame [5 x 3]
## Groups: <by row>
## 
##   V1 V2 foo
## 1  1  6  66
## 2  2  7 154
## 3  3  8 264
## 4  4  9 396
## 5  5 10 550
+4

, R. .

z

z <- function(x1, x2) {
  do.call(pmin, as.data.frame(tcrossprod(x1 * x2, pts)))
}

mutate

x %>% mutate(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

, matrixStats::rowMins ( )

library(matrixStats)

z <- function(x1, x2) {
  rowMins(tcrossprod(x1 * x2, pts))
}

x %>% mutate(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
+6
x <-as.data.frame(matrix(1:10, 5, 2))

foo <- apply(x , 1 , function(x){
  prod(x)
})

#[1]  6 14 24 36 50

class(foo)

#[1] "numeric"

df_final <- cbind(x , foo)
+1

Source: https://habr.com/ru/post/1588932/


All Articles