r语言 - 如何在具有多个列类型的整个数据集上使用跨和突变?



我试图在我的整个数据集上使用dplyr的across和case_when,所以每当它看到" strong Agree"它将其更改为数字5,"同意";到数字4,以此类推。我试着看这个答案,但我得到了一个错误,因为我的数据集有逻辑和数字列,R正确地说"同意"。不能在逻辑列中,等等

这是我的数据:

library(dplyr)
test <- tibble(name = c("Justin", "Corey", "Sibley"),
date = c("2021-08-09", "2021-10-29", "2021-01-01"),
s1 = c("Agree", "Neutral", "Strongly Disagree"),
s2rl = c("Agree", "Neutral", "Strongly Disagree"),
f1 = c("Strongly Agree", "Disagree", "Strongly Disagree"),
f2rl = c("Strongly Agree", "Disagree", "Strongly Disagree"),
exam = c(90, 99, 100),
early = c(TRUE, FALSE, FALSE))

理想情况下,我希望有一个命令可以让我遍历整个数据集。但是,如果不能这样做,我希望有一个参数允许我使用多个跨(contains())参数(即,这里包含" "或"f"。

我已经试过了,但是没有效果:

library(dplyr)
test %>%
mutate(across(.), 
~ case_when(. == "Strongly Agree" ~ 5, 
. == "Agree" ~ 4,
. == "Neutral" ~ 3,
. == "Disagree" ~ 2,
. == "Strongly Disagree" ~ 1,
TRUE ~ NA))
Error: Problem with `mutate()` input `..1`.
x Must subset columns with a valid subscript vector.
x Subscript has the wrong type `tbl_df<
name: character
date: character
s1  : character
s2rl: character
f1  : character
f2rl: character
exam: double
>`.
ℹ It must be numeric or character.
ℹ Input `..1` is `across(.)`.

我们可以使用matches来传递regex

library(dplyr)
test %>% 
mutate(across(matches('^(s|f)'), ~ case_when(. == "Strongly Agree" ~ 5, 
. == "Agree" ~ 4,
. == "Neutral" ~ 3,
. == "Disagree" ~ 2,
. == "Strongly Disagree" ~ 1,
TRUE ~ NA_real_)))

与产出

# A tibble: 3 x 8
name   date          s1  s2rl    f1  f2rl  exam early
<chr>  <chr>      <dbl> <dbl> <dbl> <dbl> <dbl> <lgl>
1 Justin 2021-08-09     4     4     5     5    90 TRUE 
2 Corey  2021-10-29     3     3     2     2    99 FALSE
3 Sibley 2021-01-01     1     1     1     1   100 FALSE

根据?across

across()可以很容易地将相同的转换应用于多个列,允许您在"data-mask"中使用select()语义。像summarise()和mutate()这样的函数

如果我们检查?select,它返回用于选择列的各种select-helpers,这些列也可以用于across

Tidyverse选择实现了R的一种方言,其中操作符使选择变量变得容易:

:用于选择一个连续的变量范围。

!用于取一组变量的补集。

,和|用于选择两组变量的交集或并集。

c()用于组合选择。

此外,您可以使用选择帮助器。一些帮助程序选择特定的列:

everything():匹配所有变量。

last_col():选择最后一个变量,可能带有偏移量。

这些帮助程序通过匹配变量名中的模式来选择变量:

starts_with():以前缀开头

ends_with():以后缀结尾

contains():包含一个字面值字符串。

matches():匹配正则表达式。

num_range():匹配数值范围,如x01, x02, x03。

这些帮助程序从字符向量中选择变量:

all_of():匹配字符向量中的变量名。所有名称必须出现,否则抛出越界错误。

any_of():与all_of()相同,只是对于不存在的名称不会抛出错误。

这个帮助器使用函数选择变量:

where():将函数应用于所有变量,并选择函数返回TRUE的变量。

我们也可以反过来做。首先使用字符5作为"5",等等…在这种情况下,我们必须使用NA_character_,这是NA字符类型最后使用type.convert(as.is = TRUE)来获取整数:

library(dplyr)
test %>%
mutate(across(s1:f2rl, 
~ case_when(. == "Strongly Agree" ~ "5", 
. == "Agree" ~ "4",
. == "Neutral" ~ "3",
. == "Disagree" ~ "2",
. == "Strongly Disagree" ~ "1",
TRUE ~ NA_character_ ))) %>% 
type.convert(as.is = TRUE)
# A tibble: 3 x 8
name   date          s1  s2rl    f1  f2rl  exam early
<chr>  <chr>      <int> <int> <int> <int> <int> <lgl>
1 Justin 2021-08-09     4     4     5     5    90 TRUE 
2 Corey  2021-10-29     3     3     2     2    99 FALSE
3 Sibley 2021-01-01     1     1     1     1   100 FALSE

最新更新