Dpylr';s重编码功能多对1 R
我想要一个更简单的方法来重新编码向量。具体来说,我想知道是否有一种方法可以将向量传递给像Dpylr';s重编码功能多对1 R,r,dplyr,recode,R,Dplyr,Recode,我想要一个更简单的方法来重新编码向量。具体来说,我想知道是否有一种方法可以将向量传递给像dplyr这样的函数recode。我了解准旋转的基本原理,但不太了解如何合并= library(tidyverse) vec1 <- rep(LETTERS[1:7],7) #standard way vec2 <- recode(vec1, "A" = "Value1", "B" = "Value2",
dplyr
这样的函数recode
。我了解准旋转的基本原理,但不太了解如何合并=
library(tidyverse)
vec1 <- rep(LETTERS[1:7],7)
#standard way
vec2 <- recode(vec1,
"A" = "Value1",
"B" = "Value2",
"C" = "Value3",
"D" = "Value4",
"E" = "Value5",
"F" = "Value6",
"G" = "Value7"
)
vec3 <- recode(vec1,
"A" = "Value1",
"B" = "Value1",
"C" = "Value2",
"D" = "Value2",
.default = "Value other"
)
我还找到了传递两个向量并重命名所有变量的方法
recode.by.vectors <- function(x, current.names, new.names){
do.call(dplyr::recode, c(list(x), setNames(new.names, current.names)))
}
recode.by.vectors我们可以在dplyr
包中使用case\u
library(dplyr)
vec1 <- rep(LETTERS[1:7],7)
vec2 <- case_when(
vec1 %in% c("A", "B") ~ "Value1",
vec1 %in% c("C", "D") ~ "Value2",
TRUE ~ "Value other"
)
head(vec2)
# [1] "Value1" "Value1" "Value2" "Value2" "Value other" "Value other"
库(dplyr)
vec1我们可以在dplyr
包中使用case\u
library(dplyr)
vec1 <- rep(LETTERS[1:7],7)
vec2 <- case_when(
vec1 %in% c("A", "B") ~ "Value1",
vec1 %in% c("C", "D") ~ "Value2",
TRUE ~ "Value other"
)
head(vec2)
# [1] "Value1" "Value1" "Value2" "Value2" "Value other" "Value other"
库(dplyr)
vec1使用forcats
软件包(也包括在tidyverse
软件包中)
使用forcats
软件包(也包括在tidyverse
软件包中)
vec3 <- vec1
val1 <- c("A", "B")
val2 <- c("C", "D")
vec3[vec1 %in% val1] <- "Value1"
vec3[vec1 %in% val2] <- "Value2"
vec3[!vec1 %in% c(val1,val1)] <- "Value other"
library(dplyr)
vec1 <- rep(LETTERS[1:7],7)
vec2 <- case_when(
vec1 %in% c("A", "B") ~ "Value1",
vec1 %in% c("C", "D") ~ "Value2",
TRUE ~ "Value other"
)
head(vec2)
# [1] "Value1" "Value1" "Value2" "Value2" "Value other" "Value other"
library(forcats)
vec1 <- rep(LETTERS[1:7], 7)
fct_collapse(vec1,
Value1 = c("A", "B"),
Value2 = c("C", "D"),
`Value other` = c("E", "F", "G"))
fct_collapse(vec1,
Value1 = c("A", "B"),
Value2 = c("C", "D")) %>%
fct_other(keep = c("Value1", "Value2"),
other_level = "Value other")