简体   繁体   English

匹配两个数据框的两列之间的值并使用另一个值创建一个新列

[英]Match values between two columns of two dataframes and create a new column with values of another

I have the 2 dataframes below我有下面的2个数据框

    name<-c("Adam","Bill","Jack")
    value<-c(3,2,1)
    n<-data.frame(name,value)
    
    name value
    1 Adam     3
    2 Bill     2
    3 Jack     1

    id<-c("Adam","Adam","Bill","Jack","Jack")
    group<-c("A","A","A","B","B")
    e<-data.frame(id,group)

    id group
    1 Adam     A
    2 Adam     A
    3 Bill     A
    4 Jack     B
    5 Jack     B

in which I want to match the values from n$name and e$id and then create a new column group in n with the respective values found in e$group like:我想在其中匹配来自n$namee$id的值,然后在n中创建一个新列group ,其中包含在e$group中找到的相应值,例如:

name value group
1 Adam     3     A
2 Bill     2     A
3 Jack     1     B

Keep only unique rows of e and merge仅保留e的唯一行并merge

merge(n, unique(e), by.x = 'name', by.y = 'id')

#  name value group
#1 Adam     3     A
#2 Bill     2     A
#3 Jack     1     B

With dplyr :使用dplyr

library(dplyr)
n %>% inner_join(distinct(e), by = c('name' = 'id'))

You can use match :您可以使用match

n$group <- e$group[match(n$name, e$id)]
n
#  name value group
#1 Adam     3     A
#2 Bill     2     A
#3 Jack     1     B

We can use data.table我们可以使用data.table

library(data.table)
setDT(n)[unique(e), on = .(name = id)]
#     name value group
#1: Adam     3     A
#2: Bill     2     A
#3: Jack     1     B

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

相关问题 如果前两列都匹配,则将数据框的一列中的值添加到另一数据框的新列中 - adding values from one column of a data frame into a new column of another dataframe if the first two columns in both match 比较两个数据框并创建新值 - Compare two dataframes and create new values R 如果两列中的单元格值匹配,则在新数据框中创建列 - R create column in new data frame if cells values match in two columns 在减去两列中的变量后,在 dataframe 中创建一个新列,条件是另一列中的值滞后 - Create a new column in dataframe after subtracting variables in two columns conditional on values in another column lagged 如何基于两个无序列合并两个数据框的列值 - How to merge the column values of two dataframes based on two unordered columns 如何根据不同数据帧的两个ID列的匹配从数据帧列中提取值? - How to extract values from a dataframe column based on the match of two ID columns of different dataframes? 根据另外两列的值创建一个新的数据框列 - Create a new data frame column based on the values of two other columns 根据两列中的值在 R 中创建新列 - Create new column in R based upon values in two columns 匹配两个数据框/行和列的行和列并复制值 - Match rows and columns of two dataframes/tibble and copy values 按id匹配并在两个数据帧之间划分列值 - Match by id and divide column values across two dataframes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM