简体   繁体   English

在R中应用函数以比较列

[英]apply functions in R for comparing columns

I've a dataframe named df . 我有一个名为df的数据df I want to check, for each document, if the xcoordinate and ycoordinate are the same. 我想检查每个文档的xcoordinate ycoordinate是否相同。

doc <- c("doc1", "doc2", "doc3") 
xcor <- c(3,4,5,3,4,5,3,4,4)   
ycor <- c(2,6,8,2,6,8,2,6,8) 
df <- data.frame(doc,xcor,ycor) 
df

doc xcor ycor  
doc1    3    2   
doc2    4    6  
doc3    5    8 
doc1    3    2  
doc2    4    6    
doc3    5    8  
doc1    3    2  
doc2    4    6  
doc3    4    8

I'm now struggling with all the apply functions, but this doesn't result in the desire outcome. 我现在正在为所有应用功能苦苦挣扎,但这并不会导致期望的结果。
Which is 哪一个

doc1 TRUE  
doc2 TRUE  
doc3 FALSE

I don't think you need an apply function for this. 我认为您不需要apply功能。 We can count the number of repeat docs after eliminating duplicate rows: 在消除重复的行之后,我们可以计算重复文档的数量:

table(df[!duplicated(df),]$doc) == 1

 doc1  doc2  doc3 
 TRUE  TRUE FALSE

Or even shorter (@DavidArenburg): 或更短(@DavidArenburg):

table(unique(df)$doc) == 1

Well, you can still achieve it with lapply : 好了,您仍然可以使用lapply实现它:

unlist(lapply(lapply(lapply(split(df, doc), unique), nrow), `==`, 1))

Looks kind of messy, but it works. 看起来有点凌乱,但可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM