我希望通過迭代兩個資料幀來形成最終資料幀。
第一個df看起來像這樣
employee_name <- c("rob", "peter")
employee_attribute1 <- c("10", "5")
employee_attribute2 <- c("5", "5")
employee_df <- data.frame(employee_name, employee_attribute1,employee_attribute2)
第二個看起來像這樣。員工可以并且確實屬于多個組
employee_group <- c("1", "2","3" )
employee_attributes <- c("employee_attribute2", "employee_attribute2","employee_attribute1" )
group_att_mapping_df <- data.frame(employee_group,employee_attributes)
我想創建一個這樣的資料框。評分條件是,如果(來自 group_att_mapping_df)employee_df的員工屬性得分employee_attributes= 10,則評分為 1,否則為 2。
employee_group| employee_name | employee_rating
1 | Rob | 2
1 | Peter | 2
2 | Rob | 2
2 |Peter | 2
3 | Rob | 1
3 | Peter | 2
需要幫助撰寫有效的 R 代碼來迭代兩個資料幀。我將附上到目前為止我撰寫的回圈的螢屏截圖。提前謝謝了。
uj5u.com熱心網友回復:
您不需要遍歷資料框。您可以使用旋轉和連接來獲得預期的輸出:
employee_df %>%
tidyr::pivot_longer(
contains("attribute"),
names_to = "employee_attributes",
values_to = "attribute_score"
) %>%
left_join(group_att_mapping_df) %>%
mutate(employee_rating = ifelse(attribute_score == 10, 1, 2)) %>%
select(employee_group, employee_name, employee_rating) %>%
arrange(employee_group)
#> Joining, by = "employee_attributes"
#> # A tibble: 6 x 3
#> employee_group employee_name employee_rating
#> <chr> <chr> <dbl>
#> 1 1 rob 2
#> 2 1 peter 2
#> 3 2 rob 2
#> 4 2 peter 2
#> 5 3 rob 1
#> 6 3 peter 2
解釋:
employee_df首先,我們將所有屬性變數作為一列進行旋轉。- 接下來,我們離開加入
group_att_mapping_df以獲取該employee_group列。 - 然后我們
employee_rating根據您的邏輯創建列:如果屬性得分為 10,則為 1,否則為 2。 - 最后,我只是通過選擇所需的列并按
employee_group.
資料不帶...
employee_name <- c("rob", "peter")
employee_attribute1 <- c("10", "5")
employee_attribute2 <- c("5", "5")
employee_df <- data.frame(employee_name, employee_attribute1,employee_attribute2)
employee_group <- c("1", "2","3")
employee_attributes <- c("employee_attribute2", "employee_attribute2","employee_attribute1")
group_att_mapping_df <- data.frame(employee_group,employee_attributes)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432505.html
上一篇:根據條件從資料框串列中洗掉行
