簡體   English   中英

如果給定年份的所有觀測值都是 NA,如何刪除面板數據中的變量?

[英]How to delete variables in a panel data if all observations for a given year are NAs?

我有一個這樣的數據框,

scores <-structure(list(student = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L, 3L), .Label = c("adam", "mike", "rose"), class = "factor"), 
    year = c(2001L, 2002L, 2003L, 2001L, 2002L, 2003L, 2001L, 
    2002L, 2003L), math = c(5L, 3L, 5L, 3L, 2L, 4L, 4L, 2L, NA
    ), english = c(2L, NA, 5L, 4L, NA, 3L, 4L, NA, 4L), history = c(NA, 
    4L, 5L, NA, 3L, 4L, NA, 5L, 3L), geography = c(4L, 5L, 5L, 
    5L, 4L, 4L, 3L, 5L, 3L)), class = "data.frame", row.names = c(NA, 
-9L))

我想刪除給定年份沒有學生得分的變量。 例如,沒有學生在 2002 年有英語分數,因此,如果我的相關年份是 2002,我想刪除變量“english”。同樣,沒有學生在 2001 年有歷史分數。所以,如果我的相關年份是 2001,變量“history”應該被刪除。 如果我的相關年份是 2003 年,則不會刪除任何變量,因為至少有一個學生(更准確地說是邁克和亞當)在變量“數學”中有分數。

為此,我構建了以下功能來完成這項工作

byearNA<-function(x,z = 3, ano = 2001) {
    matri <- data.frame(matrix(, nrow=nrow(x), ncol=(z-1)))
    matri <- x[c(1:(z-1))]
    for (i in z:ncol(x)){
        if (all(is.na(x[x[2] == ano,i]))==FALSE) {
            matri <- cbind(matri,x[i])
        }
    }
    return(matri)
}

但是,我真的相信這可以通過 R 中的本機函數(已經存在的函數)來完成。 我已經嘗試了很長時間,但找不到方法,這就是我創建自己的函數的原因。

如何使用 R 中的本機函數完成此任務?

非常感謝您提前

我不是 100% 確定你在找什么,但你試過這個嗎?

scores2 <- na.omit(scores)

這將返回有完整案例的 2 行(沒有 NA 值)

在 thelatemail 評論后添加一些行......以長格式存儲是個好主意。 如果您不想在表中看到 NA 值,您將想要使用長數據框,這里是 dplyr 方法

scores_gathered <- gather(scores, "class", "count", 3:6) 

scores_gathered <-scores_gathered %>%
  group_by(year, class) %>%
  summarize(sum = sum(count))

complete_list <- scores_gathered %>%
  drop_na(sum) %>%
  select(year, class) %>%
  mutate(has_students = "yes")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM