gpt4 book ai didi

r - 在 R 中为多个因子列创建频率表

转载 作者:行者123 更新时间:2023-12-02 05:09:41 24 4
gpt4 key购买 nike

我是 R 新手。我正在为我的工作编写一份关于常用函数/特性语法的单独手册。我的示例数据框如下:

x.sample <-
structure(list(Q9_A = structure(c(5L, 3L, 5L, 3L, 5L, 3L, 1L,
5L, 5L, 5L), .Label = c("Impt", "Neutral", "Not Impt at all",
"Somewhat Impt", "Very Impt"), class = "factor"), Q9_B = structure(c(5L,
5L, 5L, 3L, 5L, 5L, 3L, 5L, 3L, 3L), .Label = c("Impt", "Neutral",
"Not Impt at all", "Somewhat Impt", "Very Impt"), class = "factor"),
Q9_C = structure(c(3L, 5L, 5L, 3L, 5L, 5L, 3L, 5L, 5L, 3L
), .Label = c("Impt", "Neutral", "Not Impt at all", "Somewhat Impt",
"Very Impt"), class = "factor")), .Names = c("Q9_A", "Q9_B",
"Q9_C"), row.names = c(NA, 10L), class = "data.frame")

> x.sample
Q9_A Q9_B Q9_C
1 Very Impt Very Impt Not Impt at all
2 Not Impt at all Very Impt Very Impt
3 Very Impt Very Impt Very Impt
4 Not Impt at all Not Impt at all Not Impt at all
5 Very Impt Very Impt Very Impt
6 Not Impt at all Very Impt Very Impt
7 Impt Not Impt at all Not Impt at all
8 Very Impt Very Impt Very Impt
9 Very Impt Not Impt at all Very Impt
10 Very Impt Not Impt at all Not Impt at all

我的原始数据框有 21 列。

如果我想求均值(将其视为序数变量):

> sapply(x.sample,function(x) mean(as.numeric(x), na.rm=TRUE))
Q9_A Q9_B Q9_C
4.0 4.2 4.2

我想为我的数据框中的所有变量列出一个频率表。我搜索了互联网和许多论坛,发现最接近的命令是使用 sapply。但当我这样做时,它给出了全 0。

> sapply(x.sample,function(x) table(factor(x.sample, levels=c("Not Impt at all", "Somewhat Impt",            "Neutral", "Impt", "Very Impt"), ordered=TRUE)))
Q9_A Q9_B Q9_C
Not Impt at all 0 0 0
Somewhat Impt 0 0 0
Neutral 0 0 0
Impt 0 0 0
Very Impt 0 0 0

问题如何利用 sapply 根据上表为数据框中的所有列(即因子)制作频率图表?

PS 很抱歉,如果这看起来很琐碎,但我已经搜索了 2 天但没有找到答案,并尝试了所有可能的组合。可能是我搜索的不够仔细=(

非常感谢。

最佳答案

你就快到了。只要对你的函数做一个小小的改变就可以实现这一点。 function(x) ... 中的 x 需要传递给 table() 调用:

levs <- c("Not Impt at all", "Somewhat Impt", "Neutral", "Impt", "Very Impt")
sapply(x.sample, function(x) table(factor(x, levels=levs, ordered=TRUE)))

对代码进行一些重新调整也可能使其更易于阅读:

sapply(lapply(x.sample,factor,levels=levs,ordered=TRUE), table)

# Q9_A Q9_B Q9_C
#Not Impt at all 3 4 4
#Somewhat Impt 0 0 0
#Neutral 0 0 0
#Impt 1 0 0
#Very Impt 6 6 6

关于r - 在 R 中为多个因子列创建频率表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26291674/

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