我在df中有一个列,它有不同的id,有些id是复制的。我试图比较不同的id (从第一个开始),然后查看列的下一行(行)中是否存在相同的id。如果它是相同的id,那么我做一些事情,如果不去下一个id,并重复相同的。下面是df中的列
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是复制的,而有些则不是。我该怎么做?到目前为止我已经写了这个..。
first_id <- "Contig1401|m.3412"
for (i in data$V4) {
if (i=first_id) {
do something.....
} else {
do something.
}
}但我不明白我会追求这个吗。基本上我想要得到这个
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知道我该怎么做吗?
谢谢厄本德拉
发布于 2014-02-17 00:40:25
不确定这是否能满足您的要求,但这将生成最后一个表。
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发布于 2014-02-17 00:43:33
以下是一个想法:
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次的条目的评论
# 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 <- NAhttps://stackoverflow.com/questions/21818513
复制相似问题