【问题标题】:How to extract a list of columns name based on the means of their data?如何根据数据的方式提取列名列表?
【发布时间】:2020-02-27 20:11:04
【问题描述】:

我对 R 很陌生,希望我能让自己足够清楚。

我有一个包含几列因素的表格。我想为这些列中的每一列打分。然后我想计算每个分数的平均值,并显示按平均分数排名的列列表,这可能吗?

表格将是:
head(musico[,69:73])

AVIS1 AVIS2 AVIS3 AVIS4 AVIS5
1 2 1 2 3 2
2 2 5 2 3 2
3 3 2 5 5 1
4 1 2 5 5 5
5 1 5 1 3 1
6 4 1 4 5 4

我想为每个打分:

musico$score1<-0  
musico$score1[musico$AVIS1==1]<-1  
musico$score1[musico$AVIS1==2]<-0.5

然后做每列分数的平均值: score1 的平均值, score2 的平均值,...: mean(musico$score1), mean(musico$score2), ...

我的目标是创建一个按平均分数排名的标题列表(avis1、avis2、...)。

任何建议表示赞赏!

【问题讨论】:

    标签: r


    【解决方案1】:

    这是使用 base 的一种方法,尽管您还不清楚您想要什么。 score1AVIS1 有什么关系?我认为您可能遗漏了来自musico 的一些数据。

    根据提供的示例,这是一个基本的 R 解决方案。 vapply 循环遍历 data.frame 并为每一列生成平均值。然后 stackorder 只是为了使输出看起来不错的数据帧。

    music <- read.table(text = "
    AVIS1 AVIS2 AVIS3 AVIS4 AVIS5
    1 2 1 2 3 2
    2 2 5 2 3 2
    3 3 2 5 5 1
    4 1 2 5 5 5
    5 1 5 1 3 1
    6 4 1 4 5 4", header = TRUE)
    
    means <- vapply(music, mean, 1)
    stack(means[order(means, decreasing = TRUE)])
    
        values   ind
    4 4.000000 AVIS4
    3 3.166667 AVIS3
    2 2.666667 AVIS2
    5 2.500000 AVIS5
    1 2.166667 AVIS1
    

    【讨论】:

    • 非常感谢,堆栈指令正是我想要的!
    【解决方案2】:

    这就是我首先引入一个scores 向量用作查找的方法。我假设分数下降了 0.5,并且所需分数的数量取决于您的列中找到的最大级别数(即在AVIS1 中看到的 6 个级别)。

    然后使用tidyr,您可以组织您的数据集,以便您拥有包含相应级别的变量(即AVISValue)。然后使用来自dplyrmutate 函数添加一个分数变量,其中score 向量中的分数位置与Value 变量中的值匹配。从这里您可以找到与AVIS 级别对应的平均分数,并相应地排列它们并将它们放入列表中。

    music <- read.table(text = "
        AVIS1 AVIS2 AVIS3 AVIS4 AVIS5
        1 2 1 2 3 2
        2 2 5 2 3 2
        3 3 2 5 5 1
        4 1 2 5 5 5
        5 1 5 1 3 1
        6 4 1 4 5 4", header = TRUE)              # your data
    
    scores <- seq(1, by = -0.5, length.out = 6)   # vector of scores
    
    library(tidyr)
    library(dplyr)
    
    music2 <- music %>%
      gather(AVIS, Value) %>%                     # here you tidy the data
      mutate(score = scores[Value]) %>%           # match score to value
      group_by(AVIS) %>%                          # group AVIS levels
      summarise(score.mean = mean(score)) %>%     # find mean scores for AVIS levels
      arrange(desc(score.mean))                  
    
    list <- list(AVIS = music2$AVIS)              # here is the list
    
    > list$AVIS
    [1] "AVIS1" "AVIS5" "AVIS2" "AVIS3" "AVIS4"
    

    【讨论】:

    • 谢谢,不知道_gather_instruction,很有帮助。我最终使用了 Cole 提出的解决方案,因为它对我来说似乎更容易。
    • 当然。是的没问题。或许您应该只运行music2 &lt;- music %&gt;% gather(AVIS, Value) 以查看gather() 如何操作数据集。这是一个非常简洁的功能。
    猜你喜欢
    • 2015-09-30
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2021-07-31
    • 1970-01-01
    • 2019-01-11
    • 2021-07-31
    相关资源
    最近更新 更多