如何从调查数据中分离出非 0 答案

How to isolate non-0 answers from survey data

我的调查数据显示,同一个人在 6 个不同时期被问到相同的问题。有时他们回答(在这种情况下我们得到 1 到 10 的分数),有时他们不回答(在这种情况下答案是 0)。

最后,我得到了一个看起来像这样的数据框(唯一的区别是在这个例子中答案是从 1 到 2,那只是因为这样更容易生成足够数量的 0对我来说):

period_1 <- sample(0:2, 100, replace=T)
period_2 <- sample(0:2, 100, replace=T)
period_3 <- sample(0:2, 100, replace=T)
period_4 <- sample(0:2, 100, replace=T)
period_5 <- sample(0:2, 100, replace=T)
period_6 <- sample(0:2, 100, replace=T)

df <- cbind(period_1, period_2, period_3, period_4, period_5, period_6)
head(df)

     period_1 period_2 period_3 period_4 period_5 period_6
[1,]        0        2        1        1        0        1
[2,]        2        1        1        2        0        0
[3,]        1        0        2        0        1        1
[4,]        1        2        2        1        0        2
[5,]        1        1        2        2        0        2
[6,]        1        0        1        2        2        0

现在,我想看看他们的答案随着时间的推移而演变。但是对于数据框的当前结构,它有点尴尬:例如,我不能只比较第 1 期和第 2 期,因为它们并非都在第 1(或 2)期回答。 相反,我想要的是一个数据框,它在一个向量中显示他们的第一个答案,无论这个答案来自哪个时期,然后是第二个答案,依此类推……

换句话说,在survey_1中得到第一个非0答案,在survey_2中得到第二个非0答案,等等…… 这可能不是最好的解决方案,但它是最简单的解决方案,对我来说效果很好。

这可以让我把这个:

     period_1 period_2 period_3 period_4 period_5 period_6
[1,]        0        2        1        1        0        1
[2,]        2        1        1        2        1        0
[3,]        1        0        2        0        1        1

进入这个:

     survey_1 survey_2 survey_3 survey_4 survey_5 survey_6
[1,]        2        1        1        1        0        0
[2,]        2        1        1        2        1        0
[3,]        1        2        1        1        0        0

但老实说,我在 R 和一般编程方面仍然是一个大新手,我什至不知道从哪里开始实现这个目标,而且我已经坚持了一段时间没有在解决方案方面取得任何进展。

任何人都可以给我提示,甚至是示例代码,让我获得所需的结果吗?

谢谢!

我们可以使用 applyorder 通过每行的元素是否为 0:

df[] <- t(apply(df, 1, function(x) x[order(x == 0)]))

结果:

     period_1 period_2 period_3 period_4 period_5 period_6
[1,]        1        2        2        1        0        0
[2,]        2        2        1        0        0        0
[3,]        1        1        1        2        2        0
[4,]        2        2        1        2        1        0
[5,]        2        1        1        1        1        1
[6,]        2        2        1        1        0        0

数据:

df <- structure(c(0L, 2L, 1L, 2L, 2L, 0L, 1L, 0L, 1L, 2L, 1L, 2L, 0L, 
2L, 1L, 1L, 1L, 2L, 2L, 0L, 2L, 2L, 1L, 1L, 2L, 0L, 2L, 1L, 1L, 
1L, 1L, 1L, 0L, 0L, 1L, 0L), .Dim = c(6L, 6L), .Dimnames = list(
    NULL, c("period_1", "period_2", "period_3", "period_4", "period_5", 
    "period_6")))