[英]lapply functions inside each other does not work as expected
I have two lists and I must use for
and if
condition for my functions over these lists. 我有两个名单,我必须使用
for
和if
条件我在功能这些列表。 I then decide to use lapply
function. 然后,我决定使用
lapply
函数。 I used lapply
function but my code becomes so difficult and do not work. 我使用了
lapply
函数,但是我的代码变得如此困难,无法正常工作。 How can I make my code work in an easy way. 如何使我的代码以简单的方式工作。 Is there a good way to do not use many
lapply
functions. 有没有不使用很多
lapply
函数的好方法。
The idea of my code: 我的代码的想法:
> 0
. > 0
。 > 0
or not. > 0
,则为> 0
。 If it is > 0
then: 如果
> 0
则:
check the values of the second list. 检查第二个列表的值。
The last steps must applied to all the lists that I have. 最后的步骤必须应用于我拥有的所有列表。
Here is my code: 这是我的代码:
the function gave me NULL
该函数给了我
NULL
nx <- list(1, 1) ## if my list > 0 then check it
x.t <- list(c(2, 3, 4, 4), c(2, 4, 5, 6)) #the list to apply if statement on it.
lapply(nx, function(x) if (x > 0) {
do.t <- lapply(x.t, function(x) { which(x %in% c(2, 7:10))})
##check the values of my list.
lapply(nx, function(x){
lapply(1:length(x), function(i){ for (j in 1:x[[i]]){ ## here I would like j from 1 to length of x where x is a list of two elements.
if (x.t[[i]][do.t[[j]]] == 2) ## here I want to have a condition says that, if the element of each list is equal 2 then this element will have the value 2.5.
x.t[[i]] <- 2.5
}})})})
my function will includes many lists where the condition will be extend. 我的函数将包含许多将扩展条件的列表。 For example,
例如,
if (x.t[[i]][do.t[[j]]] == 2){
x.t[[i]] <- 2.5
}else{ some condition}elese{other condtion}
and so on. 等等。
the result. 结果。
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
NULL
[[1]][[2]]
[[1]][[2]][[1]]
NULL
[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
NULL
[[2]][[2]]
[[2]][[2]][[1]]
NULL
My function is so complicated and hence I provide this example very similar to my original function. 我的函数是如此复杂,因此我提供的示例与原始函数非常相似。
As a general function maybe it's better to divide the code into parts, each one doing just one thing. 作为一项通用功能,最好将代码分成几部分,每个部分仅做一件事。
Note that the lapply
passes entire vectors, the elements of the list xt
to the function. 请注意,
lapply
将整个向量(列表xt
的元素)传递给函数。 Then, complicated
loops through the elements of a vector, processing one at a time. 然后,
complicated
循环遍历向量的元素,一次处理一个。
complicated <- function(x){
for(i in seq_along(x)){
if(x[i] > 0){
if(x[i] == 2)
x[i] <- 2.5
}
}
x
}
x.t.2 <- lapply(x.t, function(x){
x <- complicated(x)
x
})
x.t.2
#[[1]]
#[1] 2.5 3.0 4.0 4.0
#
#[[2]]
#[1] 2.5 4.0 5.0 6.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.