I am new to data.table, coming from dplyr. I have the following custom function tabs:
tabs <- function(dt, x) {
tab2 <- dt[!is.na(x), ][, .(Freq = sum(nwgt0)), by = .(inc_cat, year, x)][, Prop := Freq / sum(Freq), by= .(inc_cat, year)][order(inc_cat, year)][x == 1 & !is.na(inc_cat), ] %>%
ggplot(., aes(x= year, y = Prop, color = factor(inc_cat, levels = c(1,2,3,4),labels = c("0% to 100% FPL", "101-138% FPL", "139-200% FPL", ">200% FPL")))) +
labs(color = "Income Categories") +
geom_line() +
theme_minimal() +
ylab("Weighted proportion") +
theme(
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
)
return(tab2)
}
I now wish to call the function tabs .
I have tried the following (does not work):
result <- hints_dt[ , tabs(.SD, x='internet_use')]
And receive the following error:
Error in `[.data.table`(dt[!is.na(x), ], , .(Freq = sum(nwgt0)), by = .(inc_cat, :
The items in the 'by' or 'keyby' list are length(s) (22344,22344,1). Each must be length 22344; the same length as there are rows in x (after subsetting if i is provided).
Should be using .SDcols to specify the column internet_use. If so, how do I modify my function?
Thanks,
Felippe
EDIT: per comments below, I include a reprex here. Using data from NHANES data("nhanes") I adapted the function tabs:
tabs <- function(dt, x) {
tab2 <- dt[!is.na(x), ][, .(Freq = sum(WTMEC2YR)), by = .(race, agecat, x)][, Prop := Freq / sum(Freq), by= .(race, agecat)][order(race, agecat)][x == 1 & !is.na(race), ] %>%
ggplot(., aes(x= year, y = Prop, color = factor(race, levels = c(1,2,3,4),labels = c("hispanic", "white", "black", "other")))) +
labs(color = "Race") +
geom_line() +
theme_minimal() +
ylab("Weighted proportion") +
theme(
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
)
return(tab2)
}
When I run result <- nhanes[ , tabs(.SD, x="RIAGENDR")] I was able to reproduce my error:
Error in `[.data.table`(dt[!is.na(get(x)), ], , .(Freq = sum(WTMEC2YR)), :
The items in the 'by' or 'keyby' list are length(s) (8591,8591,1). Each must be length 8591; the same length as there are rows in x (after subsetting if i is provided).
get(x)works fine for the LHS/RHS of thedata.table::`:=`operator,But your use of non-standard evaluation (NSE) within
by=will not work with this.We can use
get(by)within the NSEby=as well,But this may not always be the case. I find in these situations it is often good to recall that
by=can be either the NSE that you're using or a character vector.using
by=c(..)instead ofby=.(..). This can also work with inequality joins, wheredata.tableinternally parses and evaluates them, such asby=c("gear", paste(v, ">", otherv))(assuming we have another variableothervfor the join-comparison).From here, whatever else you do in the rest of the function should attempt to do the same thing: use
vas a character vector.Note that I have setup this function so that
vcan be length-1 or more.