填写列中相同的缺失数据

时间:2015-11-24 08:04:19

标签: r

我需要从所有列中相同的合并中填写一些缺少的数据。合并后,所有值都是NA,但我想快速填写它们,因为它们的值相同。

示例:

df <- structure(list(date = structure(c(-25932, -25931, -25930, -25929, 
-25928), class = "Date"), year = c(1899, 1899, 1899, 1899, 1899
), month = c(1, 1, 1, 1, 1), day = c(1, 2, 3, 4, 5), test1 = c(NA, 
NA, "VAR1", NA, NA), test2 = c(NA, NA, "VAR2", NA, NA), test3 = c(NA, 
NA, "VAR3", NA, NA)), .Names = c("date", "year", "month", "day", 
"test1", "test2", "test3"), row.names = c(NA, 5L), class = "data.frame")

# Tedious way, but works
df$test1 <- "VAR1"

# Desired output
    date     year month day test1 test2 test3
1 1899-01-01 1899     1   1  VAR1  VAR2  VAR3
2 1899-01-02 1899     1   2  VAR1  VAR2  VAR3
3 1899-01-03 1899     1   3  VAR1  VAR2  VAR3
4 1899-01-04 1899     1   4  VAR1  VAR2  VAR3
5 1899-01-05 1899     1   5  VAR1  VAR2  VAR3

2 个答案:

答案 0 :(得分:2)

您可以尝试以下内容:

df
#         date year month day test1 test2 test3
# 1 1899-01-01 1899     1   1  <NA>  <NA>  <NA>
# 2 1899-01-02 1899     1   2  <NA>  <NA>  <NA>
# 3 1899-01-03 1899     1   3  VAR1  VAR2  VAR3
# 4 1899-01-04 1899     1   4  <NA>  <NA>  <NA>
# 5 1899-01-05 1899     1   5  <NA>  <NA>  <NA>

df[grep("test", names(df))] <- lapply(df[grep("test", names(df))], 
                                      function(x) x[!is.na(x)][1])
df
#         date year month day test1 test2 test3
# 1 1899-01-01 1899     1   1  VAR1  VAR2  VAR3
# 2 1899-01-02 1899     1   2  VAR1  VAR2  VAR3
# 3 1899-01-03 1899     1   3  VAR1  VAR2  VAR3
# 4 1899-01-04 1899     1   4  VAR1  VAR2  VAR3
# 5 1899-01-05 1899     1   5  VAR1  VAR2  VAR3

答案 1 :(得分:2)

我们也可以使用data.table。将'data.frame'转换为'data.table'(setDT(df))。根据'test'列的索引('nm1'),我们使用每列中的非NA元素循环forset NA元素。

library(data.table)
nm1 <- grep('^test', names(df))
setDT(df)
for(j in nm1){
  set(df, i=which(is.na(df[[j]])), j=j, value= na.omit(df[[j]]))
 }
df
#          date year month day test1 test2 test3
#1: 1899-01-01 1899     1   1  VAR1  VAR2  VAR3
#2: 1899-01-02 1899     1   2  VAR1  VAR2  VAR3
#3: 1899-01-03 1899     1   3  VAR1  VAR2  VAR3
#4: 1899-01-04 1899     1   4  VAR1  VAR2  VAR3
#5: 1899-01-05 1899     1   5  VAR1  VAR2  VAR3