gpt4 book ai didi

R tidyverse 表演示

转载 作者:行者123 更新时间:2023-12-03 09:09:03 26 4
gpt4 key购买 nike

当涉及到输出表格时,我正在将统计分析脚本从 SPSS 转换为 R,尽管我不断遇到问题。我最近开始使用 tidyverse 包,因此理想情况下希望找到一个与之兼容的解决方案,但更一般地说,我希望能够针对 R 进行一些深入的表培训(如果有的话)就是这样的事情。

无论如何...这是我想要复制的表格布局:

enter image description here

本质上它是一个频率

这是一些示例数据的脚本:

i <- c(201:301)
ID <- sample(i, 200, replace=TRUE)
i <- 1:2
Category1 <- sample(i, 200, replace=TRUE)
Category2 <- sample(i, 200, replace=TRUE)
Category3 <- sample(i, 200, replace=TRUE)
df <- data.frame(ID, Category1, Category2, Category3)

现在我已经尝试过:

IDTab <- df %>%
mutate(ID = as.character(ID)) %>%
group_by(ID) %>%
summarise(C1_1 = NROW(Category1[which(Category1 == 1)])
,C1_2 = NROW(Category1[which(Category1 == 2)])
,C1_T = NROW(Category1)
,C2_1 = NROW(Category2[which(Category2 == 1)])
,C2_2 = NROW(Category2[which(Category2 == 2)])
,C2_T = NROW(Category2)
,C3_1 = NROW(Category3[which(Category3 == 1)])
,C3_2 = NROW(Category3[which(Category3 == 2)])
,C3_T = NROW(Category3))

然而,这似乎是可笑的手动操作,并且随着包含更多变量/级别,工作量显然会增加。更不用说,我已经创建了我想要的表的数据框架,而不是数据框架中的表,并且所有分类都来自命名约定,而不是任何实际的数据结构。

正如我所说...欢迎推荐硬核R table 训练。

最佳答案

如果你想制作漂亮的表格,可以看看 knitr::kablepander::panderztable::ztablextable::xtable (按通用性增加的粗略顺序)。

下面的数据处理示例不会为您提供所需的嵌套表格式,但它的扩展性应该比您当前的代码更好,并且会为您提供所需的数据。


# Make dataframe
set.seed(1234)
i <- c(201:301)
ID <- sample(i, 200, replace=TRUE)
i <- 1:2
Category1 <- sample(i, 200, replace=TRUE)
Category2 <- sample(i, 200, replace=TRUE)
Category3 <- sample(i, 200, replace=TRUE)
df <- data.frame(ID, Category1, Category2, Category3)

# Load packages
library(dplyr)
library(tidyr)

# Get the count by 'Level' (1 or 2) per 'Category' (1, 2 or 3) for each ID
df2 <- df %>%
# Gather the 'Category' columns
gather(key = Category,
value = Level,
-ID) %>%
# Convert all to character
mutate_each(funs(as.character)) %>%
# Group by and then count
group_by(ID, Category, Level) %>%
summarise(Count = n())

# Get the total count per 'Category' (1, 2 or 3) for each ID
df3 <- df2 %>%
# Group by and then count
group_by(ID, Category) %>%
summarise(Count = sum(Count)) %>%
# Add a label column
mutate(Level = 'total') %>%
# reorder columns to match df2
select(ID, Category, Level, Count)

# Finishing steps
df4 <- df2 %>%
# Bind df3 to df2 by row
rbind(df3) %>%
# Spread out 'Level' into columns
spread(key = Level,
value = Count)

# Tabulate
knitr::kable(head(df4), format = 'markdown')

|ID |Category | 1| 2| total|
|:---|:---------|--:|--:|-----:|
|201 |Category1 | 1| NA| 1|
|201 |Category2 | NA| 1| 1|
|201 |Category3 | NA| 1| 1|
|202 |Category1 | 2| NA| 2|
|202 |Category2 | 1| 1| 2|
|202 |Category3 | 2| NA| 2|

(感谢 Jenny Bryan 的代表)

关于R tidyverse 表演示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44311132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com