我有一個資料框,每個受訪者為兩個組態檔提供分數。這是資料的格式。我希望洗掉這樣的 NA,score_1并且score_2只是分數,沒有 NA。顯然,這會減少行數,消除 profile 列,并將 id 列減少到每個受訪者一個索引(而不是實際的 2 個)。有沒有辦法做到這一點?
df <- data.frame(
score_1 = c(1, NA, 4, NA, 9, NA, 12, NA),
score_2 = c(NA, 4, NA, 29, NA, 12, NA, 9),
profile = c(1, 2, 1, 2, 1, 2, 1, 2),
id = c(1, 1, 2, 2, 3, 3, 4, 4),
id_attribute = c(2, 2, 4, 4, 8, 8, 5, 5)
)
score_1 score_2 profile id id_attribute
1 1 NA 1 1 2
2 NA 4 2 1 2
3 4 NA 1 2 4
4 NA 29 2 2 4
5 9 NA 1 3 8
6 NA 12 2 3 8
7 12 NA 1 4 5
8 NA 9 2 4 5
這就是我看到最終df的方式:
df_final <- data.frame(
score_1 = c(1, 4, 9, 12),
score_2 = c(4, 29, 12, 9),
id = c(1, 2, 3, 4),
id_attribute = c(2, 4, 8, 5)
)
score_1 score_2 id id_attribute
1 1 4 1 2
2 4 29 2 4
3 9 12 3 8
4 12 9 4 5
我的意圖是用 減去每個分數,id_attribute只有在洗掉 NA 時我才能這樣做。
uj5u.com熱心網友回復:
使用tidyr::fill():
library(tidyr)
library(dplyr)
df %>%
fill(score_1) %>%
drop_na() %>%
select(!profile)
score_1 score_2 id id_attribute
1 1 4 1 2
2 4 29 2 4
3 9 12 3 8
4 12 9 4 5
uj5u.com熱心網友回復:
df %>% as_tibble() %>% pivot_longer(cols = contains("score"), names_to = c(".value", "rep"), names_sep = "_") %>% drop_na() %>% select(-profile) %>% pivot_wider(names_from = rep, values_from = score
我嘗試使用“pivot long”和“pivot broad”來洗掉 NA,但 fill() 似乎更方便。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/524532.html
標籤:r数据框呐
