我有一个返回小标题的函数。它运行正常,但我想对其进行矢量化。
library(tidyverse)
tibTest <- tibble(argX = 1:4, argY = 7:4)
square_it <- function(xx, yy) {
if(xx >= 4){
tibble(x = NA, y = NA)
} else if(xx == 3){
tibble(x = as.integer(), y = as.integer())
} else if (xx == 2){
tibble(x = xx^2 - 1, y = yy^2 -1)
} else {
tibble(x = xx^2, y = yy^2)
}
}
Run Code Online (Sandbox Code Playgroud)
mutate当我用 调用它时map2,它运行正常,给了我想要的结果:
tibTest %>%
mutate(sq = map2(argX, argY, square_it)) %>%
unnest()
## A tibble: 3 x …Run Code Online (Sandbox Code Playgroud) 这失败了:
library(tidyverse)
myFn <- function(nmbr){
case_when(
nmbr > 3 ~ letters[1:3],
TRUE ~ letters[1:2]
)
}
myFn(4)
# Error: `TRUE ~ letters[1:2]` must be length 3 or one, not 2
# Run `rlang::last_error()` to see where the error occurred.
Run Code Online (Sandbox Code Playgroud)
为什么会失败?为什么case_when其分支不能返回不同长度的向量?我想myFn工作,以便我可以做以下事情:
tibble(fruit = c("apple", "grape"),
count = 3:4) %>%
mutate(bowl = myFn(count)) %>%
unnest(col = "bowl")
Run Code Online (Sandbox Code Playgroud)
并得到
# A tibble: 5 x 3
fruit count bowl
<chr> <int> <int>
1 apple 3 a
2 apple 3 …Run Code Online (Sandbox Code Playgroud) 我经常使用tidyr::unnest。但我不使用nest; 我无法弄清楚它解决了什么问题。Nest文档给出了类似的示例
as_tibble(iris) %>% nest(-Species)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何处理结果,除了立即应用unnest它并返回iris。我想到的任何其他事情 - 比如inner_joining 它 - 如果我编辑它,我也可以做同样的事情group_by。我看过其他使用的 SO 帖子nest,例如Irregular Nest tidyverse,但它们没有启发。
nest- 它解决什么问题?您能给我举一个最直接解决问题的例子吗nest?
现在的示例代码as_tibble(iris) %>% nest(-Species)( tidyr 1.0.2) 给出了警告。在不列出每个包含的列的情况下调用它的新的、正确的方法是什么?as_tibble(iris) %>% nest(-Species, cols = everything())没用。
I have a factor that I'm using as a lookup table.
condLookup = c(hotdog = "ketchup", ham = "mustard", popcorn = "salt", coffee = "cream")
Run Code Online (Sandbox Code Playgroud)
This works as expected - I put in a 3-vector and get a 3-vector back:
condLookup[c("hotdog", "spinach", NA)]
hotdog <NA> <NA>
"ketchup" NA NA
Run Code Online (Sandbox Code Playgroud)
This too is expected, even tho the returns are all NA:
condLookup[c(NA, "spinach")]
<NA> <NA>
NA NA
Run Code Online (Sandbox Code Playgroud)
And this:
condLookup["spinach"]
<NA>
NA
Run Code Online (Sandbox Code Playgroud)
But then this surprised me - I gave …