profile
viewpoint

Ask questionsUsing tabyl with index-numbers

Feature requests

I would like to use tabyl for recurring procedures with a map()-function, looping over several variables in a data frame without naming them, but rather just have the loop access the next variable in line. It is possible with table(), but I don't like table()'s properties and rather do it with tabyl().

Here is an example with table():

map(mtcars[1:6], function(x) table(x,mtcars$gear))

With tabyl I would have to specify each tabulation, correct?

tabyl(mtcars, mpg, gear)
tabyl(mtcars, cyl, gear)
# etc.
tabyl(mtcars, wt, gear)

That seems tedious to me and I would prefer a looping-solution.

sfirke/janitor

Answer questions RachelK1994

Hi there!

I found this extremely helpful - I essentially replicated the code above for my own dataset (switching the order of variables in the table slightly) and it worked once but since I tried to clean it up slightly, I've repeatedly generated this error:

Error in :=(!!varname, value) : Check that is.data.table(DT) == TRUE. Otherwise, := and :=(...) are defined for use in j, once only and in particular ways. See help(":=").

Any help would be hugely appreciated (@jzadra I wonder whether you have any quick thoughts?)!

Best, Rachel

PS New to this forum so apologies in advance if I've missed some of the conventions.

library(readxl)
TPRdata <- read_excel("TPR-061121.xlsx")
View(TPRdata)
install.packages("janitor")
install.packages("reshape")
library(ggplot2)
library(lubridate)
library(tidyr)
library(tidyverse)
library(plyr)
library(dplyr)
library(glue)
library(purrr)
library(data.table)
library(reshape)
library(janitor)
Iffunction2 <- function(x) ifelse(x == "NA", "NA",ifelse(x == "-1", "Suppressed", ifelse(is.null(x), "Blank", ifelse(x == "Not Provided", "Not Provided", "Value"))))
TPRdata2 <- mutate_all(TPRdata, Iffunction2)
TPRdata2$state2 <- TPRdata$state
View(TPRdata2)
TPRdata2 %>% 
  pivot_longer(-state2) %>% 
  group_split(name) %>% 
  map(function(x) {
    varname <- x %>% distinct(name) %>% pull(name) 
    
    x %>% 
      rename(!!varname := value) %>% 
      tabyl(state2, !!sym(varname)) %>%
      adorn_percentages("row") %>%
      adorn_pct_formatting(digits = 2) %>%
      adorn_ns()
  })

useful!

Related questions

No questions were found.
source:https://uonfu.com/
Github User Rank List