问题
I would like to match the elements of a column in a dataframe against another dataframe.
Consider these dataframes:
A=data.frame(par=c('long A story','long C story', 'blabla D'),val=1:3)
B=data.frame(par=c('Z','D','A'),val=letters[1:3])
Each element of B column 'par' should be matched against A column par. If there is a match, it should be labeled in A. [This then gives a column of common values for merging A and B].
The desired result is therefore:
A=transform(A,label=c('A','NA','D'))
How can this be done?
Henk
回答1:
To do what you're asking for, try
A=data.frame(par=c('long A story','long C story', 'blabla D'),val=1:3)
B=data.frame(par=c('Z','D','A'),val=letters[1:3])
A$label <- NA
for (x in B$par){
is.match <- lapply(A$par,function(y) grep(x, y))
A$label[which(is.match > 0)] <- x
}
(I assumed you meant a capital A in your example A=transform(a,label=c('A','NA','D'))
; in that case, these match exactly). EDIT: I see you made that edit. They do match then.
The above method will work only if there is exactly one B that fits every A (in other words, there can be multiple As to a B but not multiple Bs to an A). This is because of the structure you want in the output.
回答2:
Hi you can do something like this :
list <- lapply(1:length(B$par),function(x) grep(B$par[x],A$par))
list
[[1]]
integer(0)
[[2]]
[1] 3
[[3]]
[1] 1
label <- rep("NA",length(list))
B$par <-as.character(B$par)
label[unlist(list)] <- B$par[which(list != "integer(0)")]
label
[1] "A" "NA" "D"
A <- transform(A,label=label)
A
par val label
1 long A story 1 A
2 long C story 2 NA
3 blabla D 3 D
Hope this helps.
回答3:
The approach I thought of:
M <- lapply(strsplit(as.character(A$par), " "), function(x) x[x %in% B$par])
M[sapply(M, function(x) {identical(x, character(0))})] <- NA
A$label <- unlist(M)
A
par val label
1 long A story 1 A
2 long C story 2 <NA>
3 blabla D 3 D
Microbenchmarked the answers here and here are the results:
Unit: microseconds
expr min lq median uq max
1 EDWARD() 1638.815 1678.934 1698.061 1726.983 4973.823
2 SONAL() 705.348 725.874 734.738 747.334 2085.721
3 TLM() 268.705 281.300 287.831 294.362 1465.744
4 TRINKER() 156.278 168.407 173.538 177.737 1331.391

回答4:
Without loops in a handy function:
findkey <- function(key,terms) {
result <- sapply(as.character(key),function(x) grepl(x,terms))
result <- apply(result,1,function(x) names(x)[x==TRUE])
result[(lapply(result,length)==0)] <- NA
return(unlist(result))
}
Apply to current example:
A$label <- findkey(B$par,A$par)
Result:
> A
par val label
1 long A story 1 A
2 long C story 2 <NA>
3 blabla D 3 D
来源:https://stackoverflow.com/questions/11667734/r-check-elements-of-vector-against-other-vector