提问人:KellyF 提问时间:10/22/2023 最后编辑:KellyF 更新时间:10/27/2023 访问量:77
在 R 的管道中为 mutate 函数传递一个字符串变量
Pass a string variable in a loop within in a pipe in R for the mutate function
问:
我无法在下面 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
答:
1赞
AndS.
10/23/2023
#1
在我看来,您只想从一串变量中对变量进行热编码。这是我要做的:
library(tidyverse)
subData <- tibble(ColumnName = c("R;Python;Rust", "Go;R"))
List<-c("Go","Rust")
add_binary_col <- function(data, checks){
data |>
mutate(lang = str_split(ColumnName, ";"),
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
#> ColumnName 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
#> ColumnName 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
#> ColumnName Python Rust
#> <chr> <dbl> <dbl>
#> 1 R;Python;Rust 1 1
#> 2 Go;R 0 0
评论
0赞
KellyF
10/23/2023
感谢您提供此代码,我很高兴它有效。我仍然希望能够通过 mutate 函数中的 x 变量传递列表,并让它与上述更容易理解的代码一起使用。mutate(x = case_when( str_detect(ColumnName, “x”)。
0赞
KellyF
10/23/2023
我在这个线程中找到了解决方案!stackoverflow.com/questions/56917704/......你
评论
subData
x
mutate
subData