lapply with anonymous function call to svytable results in object 'x' not found

前端 未结 1 1797
一个人的身影
一个人的身影 2021-01-23 04:08

I have a survey data set that I\'m creating contingency tables for. Each column in the data frame is a question and generally speaking, the questions tend to group together. S

相关标签:
1条回答
  • 2021-01-23 04:30

    Ok, well, it seems the svytable function is picky and will only look up data in the design object. It doesn't seem to look for x in the enclosing environment. So an alternative approach is to dynamically build the formula. So instead of passing in the columns of data themselves, we pass in names of columns form the data.frame. Then we plug those into the formula and then they are resolved by the design object which points to the original data.frame. Here's a bit of working code using your sample data

    lapply(names(dat)[1:9], function(x) round(prop.table(
        svytable(bquote(~.(as.name(x)) + seg_2), dat_weight),
    2),3)*100)
    

    So here we use bquote to build the formula. The .() allows us to plug in expressions and here we take the character value in x and convert it to a proper name object. Thus is goes from "r3a_9" to r3a_9.

    0 讨论(0)
提交回复
热议问题