【发布时间】:2023-03-15 20:30:01
【问题描述】:
我正在尝试使此代码适用于外部变量:
#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 的评论中指出的那样。)
【问题讨论】:
-
根据您的数据,输出将只有 5 个元素,因为您的输入行数为 5
-
另外,不知道你为什么要重复,而不是
graphData %>% summarise(out = prop.table(questionr::wtd.table(y, weights = ponde))) %>% filter(row_number() <= nFinal),然后你可能会重塑为“宽”