简体   繁体   English

如何在R的数据框中添加不同长度的列?

[英]How to add a column of different length to a data frame in R?

I have two DFs as following:我有两个 DF,如下所示:

df1 df1


ID Borrower
 1   A 
 2   A 
 3   A

df2 df2


ID Borrower Category
 1    A        X 
 1    A        X 
 1    A        X 
 2    A        X 
 2    A        X 
 2    A        X 
 3    A        X 
 3    A        X 
 3    A        X

I want to get the third column of df2 and add it to the first df.我想获取 df2 的第三列并将其添加到第一个 df 中。 The final result that I want to get is something as following:我想要得到的最终结果如下:

ID Borrower Category 
1     A       X 
2     A       X 
3     A       X

I tried df3<-left_join(df1, df2, by="ID", all=FALSE) but is not working.我试过df3<-left_join(df1, df2, by="ID", all=FALSE)但没有用。 This code produces to me something similar like df2 (so ID=1,1,1,2,2,2,3,3,3).这段代码对我产生了类似df2的东西(所以 ID=1,1,1,2,2,2,3,3,3)。 How can I add the column "Category" and get the desired result as presented above?如何添加“类别”列并获得如上所示的所需结果? Thank you:):)谢谢:):)

This is because you have duplicate values in df2 .这是因为您在df2中有重复的值。 You could do:你可以这样做:

library(tidyverse)
df1 <- tibble::tribble(
         ~ID, ~Borrower,
              1 ,  "A",
              2 ,  "A",
              3 ,  "A"
         )

df2 <- tibble::tribble(
         ~ID, ~Borrower, ~Category,
          1L,       "A",       "X",
          1L,       "A",       "X",
          1L,       "A",       "X",
          2L,       "A",       "X",
          2L,       "A",       "X",
          2L,       "A",       "X",
          3L,       "A",       "X",
          3L,       "A",       "X",
          3L,       "A",       "X"
         )

df1 %>% 
  left_join(distinct(df2)) 

Joining, by = c("ID", "Borrower")
# A tibble: 3 x 3
     ID Borrower Category
  <dbl> <chr>    <chr>   
1     1 A        X       
2     2 A        X       
3     3 A        X 

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

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