[英]How to randomly select column that does not contain a specific value in Excel or SPSS
誰知道Excel公式,VBA或SPSS語法可以執行以下操作:
在數據集或電子表格中創建一個新變量/列,該變量/列由隨機選擇的列(從1-42列的范圍)的列號(或列標題)填充,只要該列中給定行的值不包含99。
在Excel中,我可以執行第一步,創建隨機數並將其與列匹配,但是如果初始匹配的列包含值99,我不知道如何(或盡可能)“重新滾動”新的隨機數。
我的公式用於生成1到42之間的隨機數以標識列:AQ = RANDBETWEEN(1,3)
對於使用9行虛擬數據的Excel中的行:= HLOOKUP(AQ,$ A $ 1:$ AP $ 9,2,FALSE)
這是一個如何重新滾動的示例...對於給定的行,我選擇了10
但是您可以根據需要進行更改
編輯-現在通過givenRow
循環循環:
Sub test()
Dim randCol As Integer
Dim givenRow As Long
Dim saveCol As Integer: saveCol = 44 ' where to store results
With ThisWorkbook.Worksheets("your sheet name")
For givenRow = 1 To 100
Do While True
' get column between 1 and 42
randCol = Int(42 * Rnd + 1)
' if not 99 exit
If .Cells(givenRow, randCol).Value <> 99 Then Exit Do
Loop
' store results in saveCol for givenRow
.Cells(givenRow, saveCol).Value = randCol
Next
End With
End Sub
您可以使用Python在SPSS中進行以下操作:
begin program.
import spss, spssaux
import random
# get variable list
vars = spssaux.VariableDict().expand(spss.GetVariableName(0) + " to " + spss.GetVariableName(spss.GetVariableCount()-1))
proceed = True
breakcount = 0
while proceed:
# generate random integer between 0 and variable count -1, get random variable's
# name and index-position in dataset
rng = random. randint(0,spss.GetVariableCount() - 1)
ranvar = spss.GetVariableName(rng)
ind = int(vars.index(ranvar))
# read data from random variable, if value 99 is stored in the variable, go back to the top. if not, compute variable
# random_column = column number (index +1 NOT index)
randat = spss.Cursor([ind])
d = randat.fetchall()
randat.close()
data = [str(x).strip('(),') for x in d]
breakcount += 1
if "99.0" not in data:
spss.Submit("compute random_column = %s." %(ind + 1))
proceed = False
elif breakcount == 42:
break
end program.
它遍歷隨機變量,直到找到一個沒有值99的變量,然后計算包含列號的新變量。
編輯:添加了一個中斷條件,以便它不會無限循環,以防萬一每個變量都包含一個99
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.