rdplyrsumproductcross-product# Is there a way to apply a crossproduct to a new column in R using mutate?

I have a dataframe of all 1's and 0's, and a vector related to each column in the data frame, and I want to create a new column in the data frame that is the sumproduct of each row in the data frame and the vector. Consider this example:

```
dataframe <- data.frame(a = c(1, 1, 1), b = c(0, 1, 0), c = c(1, 1, 0))
> dataframe
a b c
1 1 0 1
2 1 1 1
3 1 0 0
> nums <- c(100, 200, 300)
> nums
[1] 100 200 300
```

I then would want a column d to equal (400, 600, 100). I know I can do this by writing a loop, but am trying to use mutate and crossprod and am getting the error "requires numeric/complex matrix/vector arguments"

Thanks!

Solution

You could do:

```
dataframe %>% mutate(d = as.matrix(.) %*% nums)
#> a b c d
#> 1 1 0 1 400
#> 2 1 1 1 600
#> 3 1 0 0 100
```

or

```
dataframe %>% mutate(d = crossprod(t(as.matrix(.)), nums))
#> a b c d
#> 1 1 0 1 400
#> 2 1 1 1 600
#> 3 1 0 0 100
```

- running a PCA on a RasterStack in R
- How can I extract a value from a dataframe based on a range of values?
- Confidence Interval for Some (But Not All) Interaction Terms in a Polynomial Interacted with a Binary Treatment
- Avoiding crazy lines while mapping in r
- Overlay points on top of violin plot
- Add percentage labels to geom_col()
- How to place a js inside a swiper with appendTo()?
- How to make a single plot from two dataframes with ggplot2
- Error in installing "TopicModels" package in Google Colab
- Identify connected subnetworks (R-igraph)
- Adding labels to geom_col()
- Legend title in ggplot2
- R list files with multiple conditions
- R - getting count of maximum-sized sub-group when summarising at prior group_by level
- Problems when running GDC_prepare in R
- Filtering files with names starting with a specific string
- Mutate a vector within a pipe chain
- How to sum a variable by group
- Using hex code to change text color in RMarkdown PDF (R)
- How to Remove Degree and Cardinal Direction Symbols from ggplot Coordinate Axes
- rstan and brms cause R and RStudio session abort
- How to change the plot background color generated by plot(effect(...)) in grey with white grid in R？
- SQL query on arrow duckdb workflow in R
- Venn diagram with duplicated elements
- R- Filter by time closest to midnight
- Difference between rlm() and lm_robust
- Is there a way to combine sorting an rhandsontable and removing from an rhandsontable?
- Split violin plot with ggplot2
- ggbarplot top of one bar does not align with its error bar
- read file from google drive