![](/img/trans.png)
[英]How can I design an r function that selects specific elements from a list of lists, and returns a dataframe as an output
[英]How can I write a function that returns odd numbers only from a list of integers, using R language?
如何使用R语言编写一个仅从整数列表中返回奇数的函数? 到目前为止,我已经尝试过
function3 <- function(x){
x<-as.integer(x)
if (x %% 2 ==1) {
return(x)
}
}
但是它不适用于列表或向量,而且我真的不知道如何更改代码,因为“ if”会抱怨条件“> has length> 1”,并且只会使用第一个元素
justodd <- function(x) x[ x %% 2 == 1 ]
justodd(4:20)
# [1] 5 7 9 11 13 15 17 19
说明:
索引中描述?Extract
(也?[
),你会发现它它可以是一个列表integer
(或integerizable numeric
)或logical
。 如果是前者,则数字必须在向量的长度内;否则, 如果是后者,则其长度应与原始向量的长度相同。 例如,
x <- 4:20 x[c(3,5,1)] # [1] 6 8 4 x[c(F,F,T,F,T,F,F,F,T,F,F,F,F,F,F,F,F)] # [1] 6 8 12
所以我们的[
-insides看起来像
x %% 2 == 1 # [1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE # [13] FALSE TRUE FALSE TRUE FALSE
然后我们根据该返回值索引原始向量x
更新资料
您提到它不能与list
作为参数使用,这表明它的替代方法较慢,但对向量和列表均适用。
justodd2 <- function(x) Filter(function(a) a %% 2 == 1, x)
vec <- 4:20
lst <- as.list(4:20)
str(vec)
# int [1:17] 4 5 6 7 8 9 10 11 12 13 ...
str(lst)
# List of 17
# $ : int 4
# $ : int 5
# $ : int 6
# $ : int 7
# $ : int 8
# $ : int 9
# $ : int 10
# $ : int 11
# $ : int 12
# $ : int 13
# $ : int 14
# $ : int 15
# $ : int 16
# $ : int 17
# $ : int 18
# $ : int 19
# $ : int 20
justodd2(vec)
# [1] 5 7 9 11 13 15 17 19
justodd2(lst)
# [[1]]
# [1] 5
# [[2]]
# [1] 7
# [[3]]
# [1] 9
# [[4]]
# [1] 11
# [[5]]
# [1] 13
# [[6]]
# [1] 15
# [[7]]
# [1] 17
# [[8]]
# [1] 19
性能比较:
microbenchmark::microbenchmark(
a = justodd(vec),
b = justodd2(vec),
c = justodd2(lst)
)
# Unit: nanoseconds
# expr min lq mean median uq max neval
# a 800 1000 26642 1100 1200 2537700 100
# b 12100 12500 24154 12700 13150 1055600 100
# c 12100 12300 23777 12500 12800 1022900 100
(忽略microbenchmark
的高mean
和max
,它们通常会受到R内部的垃圾回收的影响。如果您不知道那是什么,只需按[I believe]
按钮或用Google搜索。)
因此,最终,如果您一直在处理向量,则建议使用第一种justodd
解决方案,否则justodd2
会更安全(因为justodd(lst)
失败)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.