为 clogit 模型格式化数据

Formatting data for clogit model

我有一项调查,有 53 位受访者,每人回答 8 个问题。

目前它在 Excel 文档中,格式为:

人# |一季度 | Q2 | Q3 |第四季度 | Q5 | Q6 | Q7 | Q8

每个问题都有三个可能的答案,“1”、“2”或“3”。对于给定的人,每个问题都有一个数字表示回答。

我需要将每个人的答案转换为一个长列向量,其中三个选项中的每一个的响应都以二进制编码。因此,对于每个人,应该有 24 行(每个问题 3 行),并且对于每个问题,应该有一行带有 1(表示做出的选择)和两行带有 0。

我已经尝试在 Excel 和 R 中执行此操作,但无法在不手动输入每个值的情况下弄清楚如何执行此操作。

请告诉我有更好的方法吗?

将代码解释作为内联注释查看

Sub Demo()
    Dim wsSource  As Worksheet
    Dim wsDest As Worksheet
    Dim rSource As Range
    Dim rDest As Range
    Dim vSource As Variant

    Dim i As Long, j As Long

    '--> adjust to suit your needs
    ' set up source and destination references
    Set wsSource = Worksheets("SourceData")
    Set wsDest = Worksheets("DestData")

    '--> adjust to suit your needs
    ' Assumes source data has header in row 1, names in column A and responces in B..I
    With wsSource
        Set rSource = .Range(.Cells(2, 9), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    '--> adjust to suit your needs
    ' Assumes generated data starts as cell A1
    Set rDest = wsDest.Cells(1, 1)

    ' Get Source data
    vSource = rSource.Value

    ' Size Destination data array
    ReDim vDest(1 To UBound(vSource, 1) * 24, 1 To 2)

    ' Generate reformated data
    For i = 1 To UBound(vSource, 1) ' For each Person
        For j = 1 To 24 ' Add person name
            vDest((i - 1) * 24 + j, 1) = vSource(i, 1)
        Next
        For j = 1 To 8 ' Code 8 results
            vDest((i - 1) * 24 + (j - 1) * 3 + 1, 2) = IIf(vSource(i, j + 1) = 1, 1, 0)
            vDest((i - 1) * 24 + (j - 1) * 3 + 2, 2) = IIf(vSource(i, j + 1) = 2, 1, 0)
            vDest((i - 1) * 24 + (j - 1) * 3 + 3, 2) = IIf(vSource(i, j + 1) = 3, 1, 0)
        Next
    Next

    ' Place result on sheet
    rDest.Resize(UBound(vDest, 1), UBound(vDest, 2)) = vDest

End Sub