[英]Merging Two Datasets Using Different Column names: left_Join
我正在嘗試使用兩個單獨的列名合並兩個數據集,但它們共享相同的唯一值。 例如,數據集 1== xyzw 中的列 A,而在數據集 2 中,列的名稱是 B 但值 == xyzw。
然而,問題是在數據集 2 中,列的 B 值 == xyzw 指的是公司名稱並出現多次,具體取決於數據集中存在的該公司的員工數量。
本質上,我想創建一個新列,讓我們在數據集 1 中稱其為 C,告訴我每個公司有多少員工。
我嘗試了以下方法:
## Counting how many teachers are in each matched school, using the "Matched" column from matching_file_V4, along with the school_name column from the sample11 dataset:
merged_dataset <- left_join(sample11,matched_datasets,by="school_name")
雖然此代碼有效,但它並沒有真正為我提供每家公司的員工人數。
如果您可以提供示例數據和預期輸出,那么其他人可以更輕松地提供幫助。 盡管如此,我希望這能給你你想要的:
假設我們有這兩個數據框:
df_1 <- data.frame(
A = letters[1:5],
B = c('empl_1','empl_2','empl_3','empl_4','empl_5')
)
df_2 <- data.frame(
C = sample(rep(c('empl_1','empl_2','empl_3','empl_4','empl_5'), 15), 50),
D = sample(letters[1:5], 50, replace=T)
)
# I suggest you find the number of employees for each firm in the second data frame
df_2%>%group_by(C)%>%
summarise(
num_empl = n()
)%>% ### Then do the left join
left_join(
df_1,., by=c('B' = 'C') ## this is how you can join on two different column names
)
# A B num_empl
# 1 a empl_1 8
# 2 b empl_2 11
# 3 c empl_3 10
# 4 d empl_4 10
# 5 e empl_5 11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.