R匹配数据帧的不同行中的字符串

时间:2016-11-11 07:23:17

标签: r dataframe grep match lapply

我有一个包含条件列及其值的数据框,我有一个只有条件的数据框,我想通过匹配条件来提取它们的值。

df1:
Name    Style   Price   Style   Price   Style   Price
Gary    A       100     AB      300     B       200
Johnson AB      200     B       700     A       300
Marsha  AC      300     C       500     A       400
Watson  A       400     B       200     AB      500
Emma    C       500     B       100     BC      600 

df1 = structure(list(Name = c("Gary", "Johnson", "Marsha", "Watson", 
"Emma"), Style = c("A", "AB", "AC", "A", "C"), Price = c(100L, 
200L, 300L, 400L, 500L), Style.1 = c("AB", "B", "C", "B", "B"
), Price.1 = c(300L, 700L, 500L, 200L, 100L), Style.2 = c("B", 
"A", "A", "AB", "BC"), Price.2 = c(200L, 300L, 400L, 500L, 600L
)), .Names = c("Name", "Style", "Price", "Style.1", "Price.1", 
"Style.2", "Price.2"), class = "data.frame", row.names = c(NA, 
-5L)) 

df2:
Name    Style
Gary    AB
Johnson A
Marsha  C
Watson  B
Emma    BC

df2 = structure(list(Name = c("Gary", "Johnson", "Marsha", "Watson", 
"Emma"), Style = c("AB", "A", "C", "B", "BC")), .Names = c("Name", 
"Style"), class = "data.frame", row.names = c(NA, -5L))

desired output:
Name    Style   Price
Gary    AB      300
Johnson A       300
Marsha  C       500
Watson  B       200
Emma    BC      600

当条件在不同的列中时,我不知道如何匹配它们。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

我们可以使用melt中的data.table(可以使用多个measure columsn,然后与第二个数据集进行联接(' df2'){{1 '名称'和'样式'列。

on