【问题标题】:How to use a For loop to create new variables in a 3X450如何使用 For 循环在 3X450 中创建新变量
【发布时间】:2019-08-01 03:12:36
【问题描述】:

我正在尝试设置一个代码来分析一些数据,我对 R 比较陌生,而不是经验丰富的编码人员。我创建了一个 3 列 450ish 行变量,每 14 行它成为一个新条件。我想创建一个占用 1:14 行的 for 循环并为其创建一个新的命名变量。然后我需要检查那里的响应,尽管那不是其中的一部分。对不起,如果这看起来很简单!变量的第一列正在更改我将与之关联的名称,即列读取名称、试验 #,然后是响应。

我尝试过创建一个列表,然后将其关联起来,但没有成功。

理想情况下,我最终会得到 32 个新变量,它们都是 3x14,然后我可以将它们输入到其他东西中。

【问题讨论】:

    标签: r for-loop


    【解决方案1】:

    如果没有可复制的数据集,您不确定您要问什么。这是一个小例子,而不是两个试验,每个试验都保存在长格式中:

    set.seed(4)
    test <- data.frame(test = rep(letters[1:5], 2), test_value = sample(1:100, 10, replace=TRUE))
    test
    
       test test_value
    1     a         76
    2     b         29
    3     c         11
    4     d         96
    5     e         42
    6     a         46
    7     b         98
    8     c         59
    9     d         97
    10    e         77
    
    ## create new indicator variable for each trial of 5 tests in this case
    
    test$trial <- unlist(lapply(c("trial_1", "trial_2"), function(x) rep(x, 5)))
    test
    
       test test_value   trial
    1     a         76 trial_1
    2     b         29 trial_1
    3     c         11 trial_1
    4     d         96 trial_1
    5     e         42 trial_1
    6     a         46 trial_2
    7     b         98 trial_2
    8     c         59 trial_2
    9     d         97 trial_2
    10    e         77 trial_2
    

    ##传播数据,使每个试验有5个试验,每个试验都有一个值##

    library(dplyr); library(tidyr)
    
    test %>% group_by(trial) %>% spread(test, test_value)
    
    # A tibble: 2 x 6
    # Groups:   trial [2]
         trial       a     b     c     d     e
         <chr>   <int> <int> <int> <int> <int>
      1 trial_1    76    29    11    96    42
      2 trial_2    46    98    59    97    77
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 2015-12-26
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多