【问题标题】:Summarise with an external variable用外部变量总结
【发布时间】: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 %&gt;% summarise(out = prop.table(questionr::wtd.table(y, weights = ponde))) %&gt;% filter(row_number() &lt;= nFinal),然后你可能会重塑为“宽”

标签: r dplyr tibble summarize


【解决方案1】:

您可以将输出保存在列表中并使用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

【讨论】:

  • 我认为这应该可行!我会尝试一下并接受一下!谢谢!!
  • 它完全按照我的需要工作!谢谢!我需要更频繁地使用列表......
猜你喜欢
  • 1970-01-01
  • 2012-11-18
  • 2020-04-02
  • 2020-03-27
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
相关资源
最近更新 更多