[英]How to make a function skip an argument from a vector
Say I have the following function说我有以下功能
power<-function (number){
number^2
}
I also have a vector -z我也有一个向量 -z
z<- c(1:3, "a", 7:9) z<- c(1:3, "a", 7:9)
I would like to apply the power function over the vector variables.我想对向量变量应用幂函数。 If everything is a number, the functions works well using this code, which creates a list as I want:如果一切都是数字,则这些函数使用此代码运行良好,该代码可根据需要创建一个列表:
q<-lapply(z, FUN=power)
How do I make the function skip, if it does not find a valid argument?如果找不到有效的参数,如何使函数跳过? In this case skip "a".在这种情况下跳过“a”。 Let's say removing the odd argument is not an option for my task.假设删除奇怪的参数不是我的任务的选项。 I might also have cases when the function does not find the argument at all (eg empty space, missing tag on a web page).我也可能遇到函数根本找不到参数的情况(例如空白区域、网页上缺少标签)。 Would be nice if the solution could work for these instances as well.如果该解决方案也适用于这些实例,那就太好了。 Thanks.谢谢。
Consider creating a list
instead of a vector
as list
can have multiple types whereas vector
can have only a single class and if there is a single character
element, it returns the whole object as character
考虑创建一个list
而不是一个vector
因为list
可以有多种类型,而vector
只能有一个类,如果有一个character
元素,它将整个对象作为character
返回
z <- list(1:3, "a", 7:9)
lapply(Filter(is.numeric, z), FUN = power)
Or with map_if
或者用map_if
library(purrr)
map_if(z, .p = is.numeric, .f = power)
-output -输出
[[1]]
[1] 1 4 9
[[2]]
[1] "a"
[[3]]
[1] 49 64 81
This will try to coerce the elements of the supplied vector to numeric.这将尝试将提供的向量的元素强制转换为数字。 Values not coercible will have NA returned.不可强制的值将返回 NA。 Note that your input vector z may not be what you intended, ie it resolves to a character vector c("1", "2", "3", "a", ...) and not c(1, 2, 3, "a", 7, 8, 9).请注意,您的输入向量 z 可能不是您想要的,即它解析为字符向量 c("1", "2", "3", "a", ...) 而不是c(1, 2, 3, "a", 7, 8, 9)。
power<-function (number){
result<- as.numeric(number)^2
}
z <- c(1:3, "a", 7:9)
lapply(z, power)
[[1]]
[1] 1
[[2]]
[1] 4
[[3]]
[1] 9
[[4]]
[1] NA
[[5]]
[1] 49
[[6]]
[1] 64
[[7]]
[1] 81
We can also write a custom function that wraps power
inside lapply
.我们还可以编写一个自定义函数,将power
封装在lapply
。 Basically an equivalent of map_if
:基本上相当于map_if
:
z <- list(1:3, "a", 7:9)
lapply(z, function(x) {
if(all(is.numeric(x))) {
power(x)
} else {
x
}
})
[[1]]
[1] 1 4 9
[[2]]
[1] "a"
[[3]]
[1] 49 64 81
Try the code below试试下面的代码
power <- Vectorize(function(number) {
ifelse(is.numeric(number), number^2, number)
})
z <- list(1:3, "a", 7:9)
lapply(z, power)
which gives这使
> lapply(z, power)
[[1]]
[1] 1 4 9
[[2]]
a
"a"
[[3]]
[1] 49 64 81
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.