首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较r中列中的不同id

比较r中列中的不同id
EN

Stack Overflow用户
提问于 2014-02-16 23:56:21
回答 2查看 75关注 0票数 1

我在df中有一个列,它有不同的id,有些id是复制的。我试图比较不同的id (从第一个开始),然后查看列的下一行(行)中是否存在相同的id。如果它是相同的id,那么我做一些事情,如果不去下一个id,并重复相同的。下面是df中的列

代码语言:javascript
复制
     V4
Contig1401|m.3412
Contig1428|m.3512
Contig1755|m.4465
Contig1755|m.4465
Contig1897|m.4878
Contig1897|m.4878
Contig1757|m.4476
Contig1598|m.4011
Contig1759|m.4481
Contig1685|m.4244

正如您所看到的,有些id是复制的,而有些则不是。我该怎么做?到目前为止我已经写了这个..。

代码语言:javascript
复制
first_id <- "Contig1401|m.3412"

    for (i in data$V4) {
      if (i=first_id) {
        do something.....
      } else {
        do something.
      }
    }

但我不明白我会追求这个吗。基本上我想要得到这个

代码语言:javascript
复制
       V4          V5
Contig1401|m.3412  1
Contig1428|m.3512  1
Contig1755|m.4465  2
Contig1755|m.4465  
Contig1897|m.4878  2
Contig1897|m.4878
Contig1757|m.4476  1
Contig1598|m.4011  1
Contig1759|m.4481  1
Contig1685|m.4244  1

知道我该怎么做吗?

谢谢厄本德拉

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-17 00:40:25

不确定这是否能满足您的要求,但这将生成最后一个表。

代码语言:javascript
复制
df <- read.table(text="Contig1401|m.3412
Contig1428|m.3512
Contig1755|m.4465
Contig1755|m.4465
Contig1897|m.4878
Contig1897|m.4878
Contig1757|m.4476
Contig1598|m.4011
Contig1759|m.4481
Contig1685|m.4244",header=F,  stringsAsFactors=FALSE)

# One way
df$id <- duplicated(df$V1 , fromLast=T) + 1 
df$id[duplicated(df$V1) ] <- NA

#or
df$id <- rep(rle(df$V1)$lengths,rle(df$V1)$lengths)
df$id[duplicated(df$V1) ] <- NA
票数 3
EN

Stack Overflow用户

发布于 2014-02-17 00:43:33

以下是一个想法:

代码语言:javascript
复制
dat <- read.table(text="V4
Contig1401|m.3412
Contig1428|m.3512
Contig1755|m.4465
Contig1755|m.4465
Contig1897|m.4878
Contig1897|m.4878
Contig1757|m.4476
Contig1598|m.4011
Contig1759|m.4481",header=T)

# Find entries where the next entry is the same
# Convert TRUE values to be 2 and FALSE values to be 1 by adding +1
same.as.next <- sapply(1:length(dat[,1]),
                function(x)identical(dat[x,],dat[(x+1),]))+1

dat <- data.frame(dat,V5 = same.as.next)

dat[duplicated(dat$V4),]$V5 <- NA

编辑以解决OP对出现>2次的条目的评论

代码语言:javascript
复制
# notice Contig1755|m.4465 shows up 5 times in this example
dat.multduplicates <- read.table(text="V4
Contig1401|m.3412
Contig1428|m.3512
Contig1755|m.4465
Contig1755|m.4465
Contig1755|m.4465
Contig1897|m.4878
Contig1897|m.4878
Contig1757|m.4476
Contig1598|m.4011
Contig1759|m.4481
Contig1755|m.4465
Contig1755|m.4465",header=T)

# same as before
same.as.next <- sapply(1:length(dat.multduplicates[,1]),
            function(x)identical(dat.multduplicates[x,],dat.multduplicates[(x+1),]))+1
dat.multduplicates <- data.frame(dat.multduplicates,V5 = same.as.next)

# this approach should handle the duplicates
dat.multduplicates[which(dat.multduplicates$V5==2)+1,]$V5 <- NA
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21818513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档