使用NA计算每个值的组

时间:2016-02-22 12:38:54

标签: r

我使用此代码按四分计数行。但是当我的df包含NA时,它不起作用。我怎么能克服这个?

count <- sapply(split.default(df, 0:(length(df)-1) %/% 4), rowSums)

通常 rowSums na.rm = TRUE 但是当我在这里尝试时我得到了这个:

Error in is.data.frame(x) : argument "x" is missing, with no default

我尝试了不同版本的lapply,sapply或apply,但没有人工作。我只是一个首发,所以它会非常简单,但我无法取得成功。

提前致谢。

编辑: 小例子:

id <- 1:12
b <- c(0,0,1,0,0,1,1,0,0,0,1,1)
df <-data.frame(b,b,b,b,b,b,b,b,b,b,b)
df$yeni <- sapply(split.default(df, 0:(length(df)-1) %/% 4), rowSums)
#   b b.1 b.2 b.3 b.4 b.5 b.6 b.7 b.8 b.9 b.10 yeni.0 yeni.1 yeni.2
#1  0   0   0   0   0   0   0   0   0   0    0      0      0      0
#2  0   0   0   0   0   0   0   0   0   0    0      0      0      0
#3  1   1   1   1   1   1   1   1   1   1    1      4      4      3
#4  0   0   0   0   0   0   0   0   0   0    0      0      0      0
#5  0   0   0   0   0   0   0   0   0   0    0      0      0      0
#6  1   1   1   1   1   1   1   1   1   1    1      4      4      3
#7  1   1   1   1   1   1   1   1   1   1    1      4      4      3
#8  0   0   0   0   0   0   0   0   0   0    0      0      0      0
#9  0   0   0   0   0   0   0   0   0   0    0      0      0      0
#10 0   0   0   0   0   0   0   0   0   0    0      0      0      0
#11 1   1   1   1   1   1   1   1   1   1    1      4      4      3
#12 1   1   1   1   1   1   1   1   1   1    1      4      4      3

当我的数据集就像这个

时,我的代码不起作用
d <- c(0,NA,1,0,0,1,1,0,0,0,1,1)
df <-data.frame(b,b,b,b,b,b,b,b,b,b,b,d,d)

1 个答案:

答案 0 :(得分:1)

我会将df设为数组,然后使用rowSums

b <- c(0,0,1,0,0,1,1,0,0,0,1,1)
d <- c(0,NA,1,0,0,1,1,0,0,0,1,1)
df <-data.frame(b,b,b,b,b,b,b,b,b,b,b,d,d)
#convert to matrix
a <- as.matrix(df)
#fill with NA values and convert to array
i <- nrow(a)
j <- ceiling(ncol(a) / 4)
length(a) <- i * j * 4
dim(a) <- c(i, j, 4)
#rearrange dimensions of array
a <- aperm(a, c(1,3,2))
#calculate the sums
rowSums(a, na.rm = TRUE, dims = 2)
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    0    0    0    0
# [3,]    4    4    4    1
# [4,]    0    0    0    0
# [5,]    0    0    0    0
# [6,]    4    4    4    1
# [7,]    4    4    4    1
# [8,]    0    0    0    0
# [9,]    0    0    0    0
#[10,]    0    0    0    0
#[11,]    4    4    4    1
#[12,]    4    4    4    1