R - 检查矢量对其他矢量的元素 [英] R - check elements of vector against other vector

查看:156
本文介绍了R - 检查矢量对其他矢量的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



考虑这些数据框:

  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])

B列'par'的每个元素应与A列par相匹配。
如果有匹配的话,应该在A中标注。
[这会给出一列用于合并A和B的公共值。]

<因此,希望得到的结果是:

$ $ $ $ $ $ $ $ $ $ A $变换(A,label = c('A','NA', 'D'))

这怎么办?



Henk

解决方案

要做你想要的东西,试试

  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
}

(我假设你的意思是大写A在你的例子中 A = transform(a,label = c('A','NA','D'));在这种情况下,它们完全匹配)。编辑:我看到你做了编辑。他们确实匹配。



上述方法仅适用于只有一个B适合每个A的情况(换句话说,可以有多个对B而言不是多个B到A)。这是因为你在输出中需要的结构。


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

解决方案

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.

这篇关于R - 检查矢量对其他矢量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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