如何使用单个向量在R中构建函数,该向量对向量进行排序,并返回n x n矩阵,如果i优先于j,则返回1,否则返回0 到目前为止,我有这个......
preferences <- matrix(nrow = n,ncol = n)
convert <- function(n){
for (i in 1:length(n)){
for (j in 1:length(n)){
## If ith element < jth element then TRUE
if (preferences[i,j] <- preferences[i] < preferences[j]){
1
}else if (preferences[i]==preferences[j]){
0
} else{
0}
}
}
print(preferences[i,j])
}
convert(c(8,1,3))
答案 0 :(得分:1)
使用Workbooks.OpenText
Sub ImportPrepayment2()
Dim fpath As Variant
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim Text As String
On Error GoTo terminatemsg
Set wb = Excel.ActiveWorkbook
Set ws = Excel.ActiveSheet
fpath = Application.GetOpenFilename(Filefilter:="text Files(*.txt; *.txt), *.txt; *.txt", Title:="open")
If fpath = False Then Exit Sub
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Text = getTextfileData(fpath)
If Len(Text) Then
ProcessData Text
AdjustDates
Else
MsgBox fpath & " is empty", vbInformation, "Import Cancelled"
Exit Sub
End If
Columns.EntireColumn.AutoFit
Sheets(1).Move Before:=wb.Sheets(1)
terminatemsg:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Err.Number <> 0 Then MsgBox Err.Number & " " & Err.Description
End Sub
Sub ProcessData(Text As String)
Dim x As Long, y As Long, z As Long
Dim data, vLine
data = Split(Text, vbCrLf)
x = 2
Range("A1:R1").Value = Array("Supplier Name", "Supplier Number", "Inv Curr Code CurCode", "Payment CurCode", "Invoice Type", "Invoice Number", "Voucher Number", "Invoice Date", "GL Date", "Invoice Amount", "Withheld Amount", "Amount Remaining", "Description", "Account Number", "Invoice", "Withheld", "Amt", "User")
For y = 0 To UBound(data)
If InStr(data(y), "|") Then
vLine = Split(data(y), "|")
If Not Trim(vLine(0)) = "Supplier" Then
For z = 0 To UBound(vLine)
vLine(z) = Trim(vLine(z))
If vLine(z) Like "*.*.*.*.*.*.*.*" Then vLine(z) = Left(vLine(z), InStr(vLine(z), ".") + 2)
Next
Cells(x, 1).Resize(1, UBound(vLine) + 1).Value = vLine
x = x + 1
End If
End If
Next
End Sub
Sub AdjustDates()
Dim x As Long
For x = 2 To Range("B" & Rows.Count).End(xlUp).row
If Cells(x, "R") = vbNullString Then Cells(x, "M").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Next
End Sub
Function getTextfileData(FILENAME As Variant) As String
Const ForReading = 1
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.OpenTextFile(FILENAME, ForReading)
getTextfileData = MyFile.ReadAll
MyFile.Close
End Function
如果我们需要创建对角元素,可以选择
outer
+(outer(v1, v1, FUN= '<'))
答案 1 :(得分:0)
也许您需要diag
n=c(8,1,3)
diag(n, length(n), length(n))
# [,1] [,2] [,3]
#[1,] 8 0 0
#[2,] 0 1 0
#[3,] 0 0 3
答案 2 :(得分:0)
这也有效:
vec <- c(8,1,3)
outer(vec, vec, function(x,y){ifelse(x==y, x, 0)})
[,1] [,2] [,3]
[1,] 8 0 0
[2,] 0 1 0
[3,] 0 0 3