如何 return 多个值或来自 case_when() 的小标题?
How to return multiple values or a tibble from case_when()?
我找不到 return 多个值(列)的方法,或者只是 case_when()
的一个小问题。
input <- tibble(a = c(1, 2, 3))
input %>%
mutate(
case =
case_when(
a == 1 ~ tibble(x = "case1", y = "c1"),
a == 2 ~ tibble(x = "case2", y = "c2"),
a == 3 ~ tibble(x = "case3", y = "c3")
)
)
如何根据某些正则表达式条件设置多个参数?
我们可以 return 一个 list
列,因为 mutate
期望常规列是一个 vector
,length
与行数相同原始数据
input %>%
mutate(
case =
case_when(
a == 1 ~ list(tibble(x = "case1", y = "c1")),
a == 2 ~ list(tibble(x = "case2", y = "c2")),
a == 3 ~ list(tibble(x = "case3", y = "c3"))
)
)
-输出
# A tibble: 3 x 2
# a case
# <dbl> <list>
#1 1 <tibble [1 × 2]>
#2 2 <tibble [1 × 2]>
#3 3 <tibble [1 × 2]>
这是一个奇怪的情况。我认为最好将您的多个值放在单独的列中。您可以使用 datastep()
函数来做到这一点:
library(tibble)
library(libr)
# Create sample data
input <- tibble(a = c(1, 2, 3), b = c("a", "b", "c"))
# Execute datastep
input2 <- input %>%
datastep(keep = c("a", "b", "x", "y"),
{
if (a == 1) {
x <- "case1"
y <- "c1"
} else if (a == 2) {
x <- "case2"
y <- "c2"
} else if (a == 3) {
x <- "case3"
y <- "c3"
}
})
# View results
input2
# # A tibble: 3 x 4
# a b x y
# <dbl> <chr> <chr> <chr>
# 1 1 a case1 c1
# 2 2 b case2 c2
# 3 3 c case3 c3
我找不到 return 多个值(列)的方法,或者只是 case_when()
的一个小问题。
input <- tibble(a = c(1, 2, 3))
input %>%
mutate(
case =
case_when(
a == 1 ~ tibble(x = "case1", y = "c1"),
a == 2 ~ tibble(x = "case2", y = "c2"),
a == 3 ~ tibble(x = "case3", y = "c3")
)
)
如何根据某些正则表达式条件设置多个参数?
我们可以 return 一个 list
列,因为 mutate
期望常规列是一个 vector
,length
与行数相同原始数据
input %>%
mutate(
case =
case_when(
a == 1 ~ list(tibble(x = "case1", y = "c1")),
a == 2 ~ list(tibble(x = "case2", y = "c2")),
a == 3 ~ list(tibble(x = "case3", y = "c3"))
)
)
-输出
# A tibble: 3 x 2
# a case
# <dbl> <list>
#1 1 <tibble [1 × 2]>
#2 2 <tibble [1 × 2]>
#3 3 <tibble [1 × 2]>
这是一个奇怪的情况。我认为最好将您的多个值放在单独的列中。您可以使用 datastep()
函数来做到这一点:
library(tibble)
library(libr)
# Create sample data
input <- tibble(a = c(1, 2, 3), b = c("a", "b", "c"))
# Execute datastep
input2 <- input %>%
datastep(keep = c("a", "b", "x", "y"),
{
if (a == 1) {
x <- "case1"
y <- "c1"
} else if (a == 2) {
x <- "case2"
y <- "c2"
} else if (a == 3) {
x <- "case3"
y <- "c3"
}
})
# View results
input2
# # A tibble: 3 x 4
# a b x y
# <dbl> <chr> <chr> <chr>
# 1 1 a case1 c1
# 2 2 b case2 c2
# 3 3 c case3 c3