格式化clogit模型的数据

时间:2015-01-28 08:04:26

标签: r excel choice

我对53位受访者进行了调查,每位受访者回答了8个问题。

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

人#| Q1 | Q2 | Q3 | Q4 | Q5 | Q6 | Q7 | Q8

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

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

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

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

1 个答案:

答案 0 :(得分:0)

将代码说明视为内联注释

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