JerryN - 11 months ago 47

R Question

My question is about the warning I *sometimes* get with the code. The warning is

`Warning message:`

In mapply(FUN = f, ..., SIMPLIFY = FALSE) :

longer argument not a multiple of length of shorter

The idea seems simple. I want to multiple the values in each row of a vector of column names (cn) by those in the same row of another column and replace the cn columns with the new values. I'm constructing weighted sums. The weights are foodAvailRatio.

`dt.temp <- readRDS("xxx")`

cn <- c("usda_code", "item", "foodAvailRatio","item_name", "usda_desc", "IMPACT_code", "Ref_Desc", "RetnDesc", "retentioncode_aus")

cm <- names(dt.temp)[!names(dt.temp) %in% cn]

# multiply all the columns in cm by foodAvailRatio and assign to the cm columns

dt.temp[, (cm) := Map(`*`, mget(cm), foodAvailRatio)]

With this replacement (dt.cocer.rds) for xxx, don't get the error. With a different one (dt.vege.rds) I get the error. Both have length 52. For both sum(foodAvailRatio) = 1.

I'm doing this in RStudio with Microsoft Open R v 3.3.1 on a mac.

Answer Source

I believe you're trying to multiply all the `cm`

columns by `foodAvailRatio`

?

Try this:

```
dt.temp[ , (cm) := lapply(.SD, `*`, foodAvailRatio), .SDcols = cm]
```

Note that using `foodAvailRatio`

like this will require the development version (installation instructions here) since it's not in `.SDcols`

.

In 1.9.6 (currently on CRAN), you can replace `foodAvailRatio`

with `dt.temp$foodAvailRatio`

.