我试图使这段代码工作的外部变量:
#This is the original code
library(dplyr)
library(tibble)
nFinal <- 5
graphData <- tibble(y = rep(1:nFinal,2),
ponde = runif(10, min = 0, max = 1),
)
totalData <- graphData %>%
**summarise**(val1 = prop.table(questionr::wtd.table(y, weights = ponde))[1]*100,
val2 = prop.table(questionr::wtd.table(y, weights = ponde))[2]*100,
val3 = prop.table(questionr::wtd.table(y, weights = ponde))[3]*100,
val4 = prop.table(questionr::wtd.table(y, weights = ponde))[4]*100,
val5 = prop.table(questionr::wtd.table(y, weights = ponde))[5]*100)
我想要的是能够为提供的数值完成此操作,因此最后一个val
应该依赖于外部整数nFinal
中提供的数字,如下所示:
nFinal <- 10 #or any value
totalData <- graphData %>%
summarise(val1 = prop.table(questionr::wtd.table(y, weights = ponde))[1]*100,
val2 = prop.table(questionr::wtd.table(y, weights = ponde))[2]*100,
val3 = prop.table(questionr::wtd.table(y, weights = ponde))[3]*100,
val4 = prop.table(questionr::wtd.table(y, weights = ponde))[4]*100,
val5 = prop.table(questionr::wtd.table(y, weights = ponde))[5]*100,
...
valnFinal = prop.table(questionr::wtd.table(y, weights = ponde))[nFinal]*100)
我使用dplyr
,但我会接受任何其他解决方案。
(编辑,使示例数据具有nFinal元素,正如arkun的注释所指出的那样)
您可以将输出保存在一个列表中,并使用unnest_wider
创建新的列。
library(dplyr)
library(tidyr)
graphData %>%
summarise(val = list(prop.table(questionr::wtd.table(y, weights = ponde)) * 100)) %>%
unnest_wider(val)
# `1` `2` `3` `4` `5`
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 37.2 20.0 21.8 12.2 8.92