gpt4 book ai didi

r - 有没有办法在 tidyverse 生态系统中使用循环?

转载 作者:行者123 更新时间:2023-12-04 07:52:11 27 4
gpt4 key购买 nike

我曾尝试通过 mutate 和 fct_recode 函数循环来重新编码这个问题,但没有成功。有没有办法通过 tidyverse 或任何其他方式解决它?抱歉冗长 - 我想尽可能清楚。

set.seed(2021)

df <- tibble(

a1 = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("", "Yes")),
a2 = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("", "Yes")),
b1 = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("", "Yes")),
b2 = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("", "Yes")),
d1 = gl(2, 15, labels = c("Males", "Females")),
d2 = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("Python", "R"))
)

df %>% count(a1)

# Replace "" with No

myvars <- c("a1", "a2", "b1", "b2")


df %>% mutate(a1 = factor(if_else(a1 == "", "No",
as.character(a1))),
a2 = factor(if_else(a1 == "", "No",
as.character(a1))),
b1= factor(if_else(b1== "", "No",
as.character(b1))))

#---- Attempt one (forloop)

# Desire for all the variables

for (i in myvars){

df <- df %>%
mutate(i = factor(if_else(i == "", "No",
as.character(i))))
}

df %>% count(a1) # No replacement

最佳答案

tidyverse有自己的“循环”功能。
要为多列应用函数,您可以使用 across .

library(dplyr)

df <- df %>% mutate(across(all_of(myvars),
~factor(if_else(. == "", "No", as.character(.)))))

df %>% count(a1)

# a1 n
# <fct> <int>
#1 No 12
#2 Yes 18

关于r - 有没有办法在 tidyverse 生态系统中使用循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66900216/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com