Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

r - only append list elements that are not "TRUE"

I have three lists: test1, test2, test3:

test1 <- list(`0` = "text", `1` = T)
test2 <- list(`0` = "text", `1` = "text")
test3 <- list(`0` = T, `1` = T)

In these lists i only want to keep information that is NOT TRUE. For this i am using lapply:

test1 <- lapply(test1, function(x) x[!isTRUE(x)])
test2 <- lapply(test2, function(x) x[!isTRUE(x)])
test3 <- lapply(test3, function(x) x[!isTRUE(x)])

Now, i would like to append test1, test2 and test3 to an empty list with equally named list elements. However, i only want to append enteries that are text. The text may vary and there is no way to do this by character matching. I am currently getting:

$test1
$test1$`0`
[1] "text"

$test1$`1`
logical(0)


$test2
$test2$`0`
[1] "text"

$test2$`1`
[1] "text"


$test3
$test3$`0`
logical(0)

$test3$`1`
logical(0)

desired result is:

$test1
$test1$`0`
[1] "text"


$test2
$test2$`0`
[1] "text"

$test2$`1`
[1] "text"


$test3
NULL

How can i avoid getting logical(0) and obtain my desired result?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This almost gives the desired result:

lapply(
  list(test1=test1, test2=test2, test3=test3), 
  function(x){
    Filter(Negate(isTRUE), x)
  }
)

This gives:

$test1
$test1$`0`
[1] "text"


$test2
$test2$`0`
[1] "text"

$test2$`1`
[1] "text"


$test3
named list()

The only difference is the named list() for test3. But it's possible that this behavior depends on the R version (I'm using 3.6.3).

To get NULL, apply this code to this new list:

lapply(newlist, function(x) if(length(x)) x)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.6k users

...