Home > OS >  function "." not found when creating data.table
function "." not found when creating data.table

Time:12-03

gradSummary <- function(grads) {
grads$Total[is.na(grads$Total)] <- 0
total.grads <- sum(grads$Total)
data.table[, .(SchoolPerc = round(100*sum(grads$Total)/total.grads, 2), avgRank = round(mean(grads$Rank), 0), avgSalary = round(mean(grads$Median), 2)), by = grads$Major_category][order(grads$avgRank)]



}
gradSummary(grads)

Does anyone know why this code output returns "." not found? I have loaded data.table library.

CodePudding user response:

There is a problem that you use data.table as an object. Something like this should work:

gradSummary <- function(grads) {
grads$Total[is.na(grads$Total)] <- 0
total.grads <- sum(grads$Total)
data.table::data.table(grads)[, .(SchoolPerc = round(100*sum(grads$Total)/total.grads, 2), avgRank = round(mean(grads$Rank), 0), avgSalary = round(mean(grads$Median), 2)), by = grads$Major_category][order(grads$avgRank)]
}
gradSummary(grads)

CodePudding user response:

This is not how it works. data.table is a function to create a data.table object, and what you try to is to perform some specific operations for data.table class object. But you can do this only after you made data.table object.

library(data.table)

data.table[, .(a = 1   2)]
#> Error in .(a = 1   2): could not find function "."

Correct syntax is:

library(data.table)

data.table(a = 1   2)
#>    a
#> 1: 3

In the meantime @mharinga posted answer with example specific to your code, but I'm leaving this answer, because perhaps my explanation will be helpful for you.

  • Related