如何从另一个数组的计算创建一个数组excel vba

时间:2017-06-06 19:53:07

标签: arrays excel vba excel-vba

我是编码和尝试通过VBA学习的新手。我想要做的是在程序之后计算数据集中的异常值。我的麻烦是试图识别数据集中距离均值(离群值)最远并循环k次的元素。大多数代码都非常混乱,因为我一直试图找出错误所以忽略了MsgBox和丑陋的格式。在我的代码的最后部分,我尝试从DataSet中获取元素并从均值中减去它们并将这些值存储在新数组中。之后,我将获取Diff数组中元素的绝对值,并将它们存储在一个新数组(Diff2)中。我知道我可以通过计算Diff的绝对值来绕过Diff2。当我运行代码时,我得到类型不匹配错误,经过一些调查,我意识到Diff(和Diff2)不是数组。如果有人知道如何让Diff成为一个数组或更好的解决方法,那将非常感激!

Sub CalculateOutliers()
    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim X As Integer
    Dim k As Integer
    Dim DataSet As Variant
    Dim ESDPrin As Double

    DataSet = Selection.Value
    'Copies highlighted data into DataSet variable
    'Cell A1 is (1,1) Because it starts at 0 which is out of range

    n = Selection.CountLarge
    'Counts number of entries
    'If n < 20 Then
        'MsgBox "Data set too small"
        'Exit Sub
    'End If
    'Ends Subroutine if data set is too small for this analysis

    If n < 50 Then
        k = Int(n / 10)
    Else
        k = 5
    End If
    'determines k = number of possible outliers

    mean = Application.WorksheetFunction.Average(DataSet)
    'Calculates mean of Data Set
    MsgBox mean & "Average"

    SD = Application.WorksheetFunction.StDev(DataSet)
    'Calculates Standard Deviation of Data Set

    Dim element As Variant
    Dim Diff As Variant

    For Each element In DataSet
        Diff = element - mean
        MsgBox Diff & " Difference"
    Next element

    Dim P As Integer
    Dim Outlier As Integer
    Dim Diff2 As Variant

    Diff2 = Abs(Diff)

    For P = 1 To k
        Outlier = UBound(Diff, 1)
        MsgBox Outlier
   Next P
End Sub

2 个答案:

答案 0 :(得分:3)

这里是如何创建大小为n

的Diff Array
ReDim Diff(1 To n) As Double
Dim i As Long
For Each element In DataSet
    i = i + 1
    Diff(i) = element - mean
Next element

但是,我不认为这是正确的方法。不需要Diff数组。你应该做的是,一旦你计算了meanSD,迭代DataSet数组本身,检查每个元素与均值的绝对差异,除以stdev,并比较这个比例到某个阈值(比如说2或3)来决定这个元素是否是一个异常值,在这种情况下你把它打印成异常值。像这样:

For Each element In DataSet
   If abs(element - mean) / SD > 3 Then Debug.Print "outlier: " & element
Next element

答案 1 :(得分:0)

我认为代码就像这样

invitePeersController.getGmailContacts = function(){
    console.log("I come in gmail contacts");
    var clientId = "contact key";
    var apiKey = "apiKey";
    var scopes = "https://www.googleapis.com/auth/contacts.readonly";
    authorize();
    function authorize() {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
    }
    function handleAuthorization(authorizationResult){
        invitePeersController.gmailContacts = [];
        var gmailData = [];
        if (authorizationResult && !authorizationResult.error){
            var urlContact = "https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=50000&v=3.0";
            var promiseGoogleData = HttpService.httpGetExternalLink(urlContact);
            promiseGoogleData.then(function (response) {
                var jsonChildData = response.data.feed.entry;
                for(var i=0; i<jsonChildData.length ;i++){
                    var item = {};
                    try{
                        var name = jsonChildData[i].title.$t;
                        var email = jsonChildData[i].gd$email[0].address;

                        if(name.substring(1, name.length-1) && email.substring(1, email.length-1)){
                            item ["name"] = name.substring(1, name.length-1);
                            item ["email"] = email.substring(1, email.length-1);
                            item ["id"] =  email.substring(1, email.length-1).replace(/[^a-zA-Z ]/g, "");
                        invitePeersController.gmailContacts.push(item);
                        gmailData.push(item);
                       }

                    }catch(error){
                        console.log("Error is thrown while trying to read gmail resposne");
                }

            }
            $state.go("app.inviteContacts");
            InvitePeersService.setGmailContactsData( invitePeersController.gmailContacts);

                        return response;
                    })
                    .catch(function (error) {
                        console.log("Something went terribly wrong while trying to get Gmail Data.");
                    });
                }


            }

        }