我是R的新手,我还不了解所有基本概念。任务是产生一个包含多个响应集的合并表。我正在尝试使用expss
库和循环来做到这一点。
这是R中没有循环的代码(工作正常):
#libraries
#blah, blah...
#path
df.path = "C:/dataset.sav"
#dataset load
df = read_sav(df.path)
#table
table_undropped1 = df %>%
tab_cells(mdset(q20s1i1 %to% q20s1i8)) %>%
tab_total_row_position("none") %>%
tab_stat_cpct() %>%
tab_pivot()
有10个多个响应集,因此我需要以上述方式创建10个表。然后我转置这些表并合并。为了简化代码(并学习新知识),我决定使用循环生成表。但是,没有任何效果。我一直在寻找解决方案,我认为最接近正确的解决方案是:
#this generates a message: '1' not found
for(i in 1:10) {
assign(paste0("table_undropped",i),1) = df %>%
tab_cells(mdset(assign(paste0("q20s",i,"i1"),1) %to% assign(paste0("q20s",i,"i8"),1)))
tab_total_row_position("none") %>%
tab_stat_cpct() %>%
tab_pivot()
}
仍然会导致代码上面描述的错误。
或者,将为此使用一个SPSS宏(仅发布是为了更好地表达问题,因为我必须避免使用SPSS):
define macro1 (x = !tokens (1)
/y = !tokens (1))
!do !i = !x !to !y.
mrsets
/mdgroup name = !concat($SET_,!i)
variables = !concat("q20s",!i,"i1") to !concat("q20s",!i,"i8")
value = 1.
ctables
/table !concat($SET_,!i) [colpct.responses.count pct40.0].
!doend
!enddefine.
*** MACRO CALL.
macro1 x = 1 y = 10.
换句话说,我正在寻找!concat()
R中的有效替代品。
%to%
不适合参数变量选择。有一组用于参数变量选择和分配的特殊功能。其中之一是mdset_t
:
for(i in 1:10) {
table_name = paste0("table_undropped",i)
..$table_name = df %>%
tab_cells(mdset_t("q20s{i}i{1:8}")) %>% # expressions in the curly brackets will be evaluated and substituted
tab_total_row_position("none") %>%
tab_stat_cpct() %>%
tab_pivot()
}
但是,在全局环境中将所有表存储为单独的变量不是一个好习惯。更好的方法是将所有表保存在列表中:
all_tables = lapply(1:10, function(i)
df %>%
tab_cells(mdset_t("q20s{i}i{1:8}")) %>%
tab_total_row_position("none") %>%
tab_stat_cpct() %>%
tab_pivot()
)
更新。一般来说,没有必要合并。您可以使用以下工具完成所有工作tab_*
:
my_big_table = df %>%
tab_total_row_position("none")
for(i in 1:10) {
my_big_table = my_big_table %>%
tab_cells(mdset_t("q20s{i}i{1:8}")) %>% # expressions in the curly brackets will be evaluated and substituted
tab_stat_cpct()
}
my_big_table = my_big_table %>%
tab_pivot(stat_position = "inside_columns") # here we say that we need combine subtables horizontally
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句