在 R 管道中的循环中传递字符串变量以用于 mutate 函数

问题描述 投票:0回答:1

我无法将下面 R 中的 mutate 函数中的 x 变量变为浮动变量。有人可以帮我解决此代码的问题吗?

library(dplyr)
List<-c("Go","Rust")

env <- environment()

for (i in c(1:length(List))) {

   x=List[i]

   "x" %>% assign(List[i], envir = env)
   print(x)
   subData<-subData %>% 
      mutate(x = case_when( str_detect(ColumnName, "x") ~ 1, TRUE ~ 0))
}

Rust 和 Go 是在字符串列中找到的单词,然后使用该单词创建新的列名称。这就是 mutate 函数正在做的事情。

这两行代码在我运行时有效,但当我尝试循环列表时它们不起作用。

 subData <- subData %>% 
 mutate(Rust = case_when(str_detect(LanguageWantToWorkWith, "Rust") ~ 1, 
  TRUE ~ 0))

subData <- subData %>% 
mutate(Go = case_when(str_detect(LanguageWantToWorkWith, "Go") ~ 1, TRUE 
~ 0))

谢谢你, 凯莉·菲茨帕特里克

我无法让 mutate 函数中的

x
变量循环遍历单词列表。

r loops variables floating
1个回答
0
投票

在我看来,您只想从一串变量中对变量进行单热编码。这就是我要做的:

library(tidyverse)

subData <- tibble(CoulumName = c("R;Python;Rust", "Go;R"))

List<-c("Go","Rust")

add_binary_col <- function(data, checks){
  data |>
    mutate(lang = str_split(CoulumName, ";"),
           cols = map(lang, ~checks[checks %in% .x]),
           v = 1) |>
    unnest(cols, keep_empty = TRUE) |>
    pivot_wider(names_from = cols, values_from = v, values_fill = 0) |>
    select(-lang, -starts_with("NA"))
}

add_binary_col(subData, List)
#> # A tibble: 2 x 3
#>   CoulumName     Rust    Go
#>   <chr>         <dbl> <dbl>
#> 1 R;Python;Rust     1     0
#> 2 Go;R              0     1
add_binary_col(subData, c("R", "Python", "Rust"))
#> # A tibble: 2 x 4
#>   CoulumName        R Python  Rust
#>   <chr>         <dbl>  <dbl> <dbl>
#> 1 R;Python;Rust     1      1     1
#> 2 Go;R              1      0     0
add_binary_col(subData, c("Python", "Rust"))
#> # A tibble: 2 x 3
#>   CoulumName    Python  Rust
#>   <chr>          <dbl> <dbl>
#> 1 R;Python;Rust      1     1
#> 2 Go;R               0     0
© www.soinside.com 2019 - 2024. All rights reserved.