【问题标题】:Create multiple variables from existing variables variables using a statistical method simultaneously in R在 R 中同时使用统计方法从现有变量变量中创建多个变量
【发布时间】:2021-07-24 20:23:01
【问题描述】:

使用 bloms 公式,我从现有变量创建了一个新变量,同时将它们都保留在 DF 中:

DF$R_BLR<-blom(DF$R, method = "blom")

我有 7 个其他变量(S、T、U、V、W、X、Y,用于创建新变量(S_BLR T_BLR 等)同时保留原始变量)我想执行相同的操作,想知道是否有是一种我可以一次性完成的方法,而不是按照第一个方法将它们全部输入。

现有变量在 DF 中彼此相邻(第 1-7 列)。我尝试过使用 mutate 函数,因为之前我想在其他变量中重新编码类别时,它可以工作,但这只是一个直接的转换,我不太清楚语法。

【问题讨论】:

    标签: r variables


    【解决方案1】:

    使用lapply -

    new_cols <- paste0(names(df)[1:7], '_BLR')
    df[new_cols] <- lapply(df[1:7], blom, method = "blom")
    

    【讨论】:

      【解决方案2】:

      我们可以使用dplyr::across,这里是一个例子:

      library(dplyr)
      library(rcompanion)
      
      # from `?blom`'s examples
      Value = c(709,679,699,657,594,677,592,538,476,508,505,539)
      Sex   = c(rep("Male",3), rep("Female",3), rep("Male",3), rep("Female",3))
      Fat   = c(rep("Fresh", 6), rep("Rancid", 6))
      
      Sokal = data.frame(Value, Sex, Fat)
      
      # dplyr::across with the example above (one varialbe)
      
      Sokal %>% 
        mutate(across(Value, list(BLR = ~ blom(.x, method = "blom"))))
      #>    Value    Sex    Fat  Value_BLR
      #> 1    709   Male  Fresh  1.6350393
      #> 2    679   Male  Fresh  0.7916386
      #> 3    699   Male  Fresh  1.1139372
      #> 4    657 Female  Fresh  0.3119191
      #> 5    594 Female  Fresh  0.1024905
      #> 6    677 Female  Fresh  0.5361763
      #> 7    592   Male Rancid -0.1024905
      #> 8    538   Male Rancid -0.5361763
      #> 9    476   Male Rancid -1.6350393
      #> 10   508 Female Rancid -0.7916386
      #> 11   505 Female Rancid -1.1139372
      #> 12   539 Female Rancid -0.3119191
      
      # applying this example to your data.frame
      your_df <- setNames(as.list(1:8), LETTERS[18:25]) %>% as_tibble
      
      # using tidyselect `matches()` with a regex in `across`
      your_df %>% 
        mutate(across(matches("[R-Y]"),
                      list(BLR = ~ blom(.x, method = "blom"))))
      
      # or select variables by position in `across`
      your_df %>% 
        mutate(across(1:7,
                      list(BLR = ~ blom(.x, method = "blom"))))
      

      reprex package (v0.3.0) 于 2021-07-24 创建

      【讨论】:

      • 感谢您的回复。 your_df % as_tibble 那么这是否会将 DF 中的前 8 行转换为 tibble?字母[18:25]) 是做什么的?
      • 这一行只是为了创建一个与您的数据具有相似名称的data.frame,因为您的帖子不包含任何示例数据(这会使复制问题变得更容易)。您应该忽略这一行,只需将 your_df 替换为您的实际数据。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多