识别子列表中的唯一元素并进行更改 [英] identifying unique elements in sub lists and altering

查看:76
本文介绍了识别子列表中的唯一元素并进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有以下列表":

I have the following 'list' in R:

[[1]]
[1] 17336  5246  8597  5246 17878 19701

[[2]]
[1] 19701 37748 18155  5246  8597

[[3]]
[1] 12297 19701 17878  5246 17336  8597 17878

[[4]]
[1] 17878 37748 19701 37748 12297  8597

[[5]]
[1] 19701 37748 19701 37748 19701  5246

[[6]]
[1] 19701  6254 17336 18155 19701 12297

[[7]]
[1] 19701 17878 18155 17878 18155 19701  8597

[[8]]
[1]  8597 18155

[[9]]
[1] 12450 18155  5246  8597  5246  8597

[[10]]
[1] 18155  4105  6254 17878 12297  5246

[[11]]
[1]  8597 12297

[[12]]
[1] 17878  5246 18155 17878 12297  8597

[[13]]
[1]  8597 18155

[[14]]
[1]  5246 37748 18155 12450 18155  8597

[[15]]
[1] 19701 37748  6254  8597  6254  8597 12297

[[16]]
[1] 19701 17878  4105 37748 18155 19701 12450 12297

[[17]]
[1]  6254 12450 37748 17878  5246 17878  8597

[[18]]
[1]  8597 12297 18155  5246 18155 12297

[[19]]
[1]  4105 37748 17878  5246 12450  5246 12450

[[20]]
[1] 17878 20467

[[21]]
[1] 20467

[[22]]
[1] 12450 37748 12450 17878 12450 12297

[[23]]
[1]  6254 17878 12450 12297     5  4105 27697  4105 27697

[[24]]
[1]  4105 37748 17878 20467 12450 17878 27697

[[25]]
[1]  5246 27697  5246 17336 17878  5246 12297 20467

我想找到浏览此列表的最快方法,并确定是否有任何元素是特定值,将此称为参考值".例如,如果参考值为"5",那么我想确定元素[[23]]中具有"5".我想做的就是更改该元素,使其变为:

I want to find the fastest way to look through this list and find if any of the elements are a specific value, call this the 'reference value'. For example, if the reference value is '5', then I want to identify that element [[23]] has a '5' in it. What I would like to do is alter that element so that it becomes:

[[23]] 4105 27697  4105 27697

推荐答案

使用@SymbolixAU的数据:

Using @SymbolixAU's data:

lapply(lst, function(x) tail(x, -Position(isTRUE, x==5, nomatch=-Inf)) )
#[[1]]
#[1] 1 2 3
# 
#[[2]]
#[1] 2 3 4
#
#[[3]]
#numeric(0)
# 
#[[4]]
#[1] 6

解释其工作原理:
1)中间的Position部分仅在第一次检测到5时返回索引的负数,即:

To explain how this works:
1) The middle Position part just returns the negative of the index of the first time a 5 is detected, i.e.:

sapply(lst, function(x) -Position(isTRUE, x==5, nomatch=-Inf) )
#[1] Inf Inf  -3  -2

2)tail(x, -n)只是从向量中删除第一个n值.改为使用Inf运行时,不会删除任何内容.因此,为什么在没有找到5的情况下在实例中使用Inf.

2) tail(x, -n) just removes the first n values from a vector. When run with Inf instead, nothing is removed. Hence why Inf is used in the instance when no 5 is found.

这篇关于识别子列表中的唯一元素并进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆