【问题标题】:Create Table Column From Another Vector从另一个向量创建表列
【发布时间】:2017-06-30 14:52:09
【问题描述】:

有人可以提供有关从 R 中的另一个向量创建新表列的建议吗?

我有一个名为“main”的表,其中包含测试类型和测试数量。我想创建一个新列来分配测试值。

Test Type    Number of Tests    Test Value
    a               1               
    b               4   
    c               3
    d               2

测试值按顺序存储在另一个向量 x

对应测试类型的测试值等于多个测试值的平均值。例如测试a类型为0.1,测试b类型为(0.2+0.2+0.3+0.2)/4,测试c类型为(0.6+0.5+0.6)/3,测试d类型为(1.2+1.3)/2 .

以下是我的代码:

idx_low <- 1
number_vector <- numeric()
for (value in main[[2]]) {
    idx_high <- idx_low+value-1
    number <- mean(x[idx_low:idx_high])
    number_vector <- c(number_vector, number)
    idx_low <- idx_high+1
}
main[[3]] <- number_vector  

【问题讨论】:

    标签: r vector


    【解决方案1】:

    这个怎么样:

    library("dplyr")
    main = data.frame(test_type = letters[1:4],
                      num_tests = c(1,4,3,2),
                      stringsAsFactors = FALSE)
    test_scores = c(0.1, 0.2, 0.2, 0.3, 0.2, 0.6, 0.5, 0.6, 1.2, 1.3)
    labels = c()
    for(i in 1:nrow(main)){
      labels = c(labels, rep(x = main$test_type[i], times = main$num_tests[i] ))
    }
    
    test_scores = data.frame(scores = test_scores,
                             test_type = labels) %>% 
      group_by(test_type) %>% 
      summarise(avg_score = mean(scores)) %>% 
      right_join(main)
    

    【讨论】:

    • 为什么要使用 for 循环? rep 也适用于向量。 labels &lt;- rep(main$test_type,main$num_tests)
    • 不错的组。谢谢。
    【解决方案2】:
    main <- as.data.frame(c(main,test))
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2016-05-22
    • 2011-02-05
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2022-01-08
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多