在R中,我有一个字符列表:
> column_list
> "C", "F", "G", "M", "O", "Y", "Z"
> typeof(column_list)
> "character"
我希望在列表中的每个项目上以定义的长度N的0填充它,以便它是一个看起来像这样的矩阵:
C F G M O Y Z
0 0 0 0 0 0 0
0 0 0 0 0 0 0
... n times
然后我想将此矩阵(使用cbind?)组合到另一个矩阵,并按字母顺序排序。
A B D E H I ...
.1 .2 .1 .5 .1 .1
0 .2 .3 0 0 .2
.1 0 .1 .1 0 .3
...
这样我的新矩阵看起来像这样
A B C D E F G H I ...
.1 .2 0 .1 .5 0 0 .1 .1
0 .2 0 .3 0 0 0 0 .2
.1 0 0 .1 .1 0 0 0 .3
...
如何执行这两个步骤?
答案 0 :(得分:0)
您可以使用以下步骤作为指导来实现代码或实现功能。
首先,将 import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import * as _ from 'lodash';
import { PropertyType, MessageType } from '../../../entity-common';
import { ListService, LabelService } from '../../../app/services';
import { EntityListHelper } from '../../../helpers';
import { PageChangeEvent, SelectAllCheckboxState } from '@progress/kendo-angular-grid';
import { Map } from 'immutable';
@Component({
selector: 'mgr-entity-list-kendo-grid',
templateUrl: './entity-list-kendo-grid.component.html',
providers: [EntityListHelper]
})
export class EntityListKendoGridComponent implements OnInit, OnChanges {
@Input() options: any;
@Input() endpoint: any;
@Input() formReadOnly: boolean;
@Input() selectedView: any;
@Input() multiSelectValue: any;
@Input() selectedAllPages: any;
@Input() multiSelectField: any;
@Input() inlineAddAction: any;
@Input() inlineEditAction: any;
@Input() multiAddAction: any;
@Output() lookupSelectedEvent: EventEmitter<any> = new EventEmitter<any>();
@Output() multiSelectIdsEvent: EventEmitter<any> = new EventEmitter<any>();
multiSelectIds: Array<number> = [];
kendoSelectedItems: Array<any> = [];
PropertyType = PropertyType;
MessageType = MessageType;
newItem: any = { rowProperties: { editMode: false }, record: undefined };
isSorting: boolean;
collapsed = false;
multiSelectSeparator = ';';
searchParams = {
Criteria: [],
AdvancedConditions: ''
};
public checkboxOnly = false;
public mode = 'multiple';
public mySelection: number[] = [];
public selectAllState: SelectAllCheckboxState = 'unchecked';
public kendoGridPageDataSkip = 0;
public pageSizeOptions = [];
public filter: any;
constructor(
private listService: ListService,
private labelService: LabelService,
private helper: EntityListHelper,
private formBuilder: FormBuilder) {
}
ngOnInit() {
this.setupBase();
if (this.options.displayPageSizeSelector) {
this.pageSizeOptions = [5, 20, 50, 100, 200];
}
}
ngOnChanges() {
this.multiSelectIds = [];
this.selectedAllPages = [];
this.kendoSelectedItems = [];
this.selectedView = this.helper.getSelectedView(this.options);
this.options.formLayout = this.selectedView ? this.selectedView.formLayout : null;
this.setupBase();
}
private setupBase() {
if (this.options.actions) {
this.inlineAddAction = this.options.actions.find(action => action.action === 'inlineAdd');
this.inlineEditAction = this.options.actions.find(action => action.action === 'inlineEdit');
this.multiAddAction = this.options.actions.find(action => action.action === 'newFromLookup');
}
if (this.multiSelectIds.length === 0) {
this.selectAllState = 'unchecked';
}
}
getCount(): number {
if (this.options.records) {
return this.options.totalCount;
}
return 0;
}
isReadOnly() {
return this.options.readOnly || this.formReadOnly;
}
hasCheckbox(): boolean {
if (this.options.actions &&
this.options.actions.length > 0 && !this.options.disableRowSelector) {
return true;
} else {
return false;
}
}
rowClick(item) {
if (this.multiSelectField) {
this.updateMultiSelectItems(item);
return;
} else if (!this.options.rowClickAction) {
return;
} else if (this.options.rowClickAction.action.toLowerCase() === 'selectlookupvalue') {
this.lookupSelectedEvent.emit(item);
}
this.options.rowClickAction.actionFunction(item);
}
// multiSelect logic
updateMultiSelectItems(item) {
if (this.multiSelectIds.indexOf(item.record.id) === -1) {
this.addMultiSelect(item);
} else {
this.removeMultiSelect(item);
}
this.multiSelectIdsEvent.emit(this.multiSelectIds);
}
addMultiSelect(item) {
if (this.multiSelectValue !== '') {
this.multiSelectValue += this.multiSelectSeparator + ' ';
}
this.multiSelectValue += item.record[this.multiSelectField];
this.multiSelectIds.push(item.record.id);
}
removeMultiSelect(item) {
this.multiSelectValue = this.multiSelectValue.replace(item.record[this.multiSelectField], '');
this.multiSelectValue = this.multiSelectValue.replace(this.multiSelectSeparator + ' ', '');
this.multiSelectIds.splice(this.multiSelectIds.indexOf(item.record.id), 1);
if (this.selectedAllPages.indexOf(this.options.page) >= 0) {
this.selectedAllPages.splice(this.selectedAllPages.indexOf(this.options.page), 1);
}
}
multiSelectAllCurrentPage() {
if (this.selectedAllPages.indexOf(this.options.page) === -1) {
this.selectedAllPages.push(this.options.page);
for (let i = 0; i < this.options.records.length; i++) {
if (this.multiSelectIds.indexOf(this.options.records[i].record.id) === -1) {
this.addMultiSelect(this.options.records[i]);
}
}
} else {
this.selectedAllPages.splice(this.selectedAllPages.indexOf(this.options.page), 1);
for (let i = 0; i < this.options.records.length; i++) {
if (this.multiSelectIds.indexOf(this.options.records[i].record.id) >= 0) {
this.removeMultiSelect(this.options.records[i]);
}
}
}
this.multiSelectIdsEvent.emit(this.multiSelectIds);
}
onListFilterSearch() {
this.options.filterListFunction(this.searchParams);
}
getPageSize(options): number {
if (!options.displayPageSizeSelector) {
return options.pageSize;
}
return this.helper.getLookupPageSize(options);
}
getKendoRecords() {
const totalCount = this.getCount();
return {
data: this.options.records,
total: totalCount
};
}
getKendoRecordValue(property, item) {
const properties = property.propertyName.split('.');
let object = item ? item.record : this.options.records[0].record;
for (let i = 0; i < properties.length; i++) {
if (!object) {
break;
}
const propertyValue = properties[i];
object = object[propertyValue];
}
return object;
}
getKendoEditorType(property) {
switch (property.propertyType) {
case (this.PropertyType.string):
return 'string';
case (this.PropertyType.checkbox || this.PropertyType.radio || this.PropertyType.boolean):
return 'boolean';
case (this.PropertyType.integer || this.PropertyType.number):
return 'numeric';
case (this.PropertyType.date):
return 'date';
case (this.PropertyType.time):
return 'time';
default:
return 'string';
}
}
getKendoFieldName(property) {
return property.replace(/\W+/g, '');
}
cellClickHandler({ sender, rowIndex, columnIndex, dataItem, isEdited }) {
if (!isEdited) {
sender.editCell(rowIndex, columnIndex, this.createFormGroup(dataItem));
}
}
private createFormGroup(dataItem: any): FormGroup {
const newFormGroup = {};
this.selectedView.properties.forEach(property => {
newFormGroup[this.getKendoFieldName(property.propertyLabel)] = this.getKendoRecordValue(property, dataItem);
});
return this.formBuilder.group(newFormGroup);
}
formatDate() {
if (!this.options.fieldFormats) {
return '';
}
return this.options.fieldFormats.dateFormat.toUpperCase().toString();
}
formatTime() {
if (!this.options.fieldFormats) {
return '';
}
return this.options.fieldFormats.timeFormat;
}
gridCellClick(event) {
if (event.dataItem.rowProperties && event.dataItem.rowProperties !== null) {
this.rowClick(this.getRecordItembypageIdLink(event.dataItem.record.id, event.dataItem.rowProperties.pageIdLink));
} else {
this.rowClick(this.getRecordItem(event.dataItem.record.id));
}
}
getRecordItembypageIdLink(id, pageIdLink) {
return this.options.records.find(item => item.record.id === id && item.rowProperties.pageIdLink === pageIdLink);
}
getRecordItem(id) {
return this.options.records.find(item => item.record.id === id);
}
public onSelectedKeysChange(event) {
this.multiSelectIds = this.kendoSelectedItems.map(record => record.id);
this.multiSelectIdsEvent.emit(this.multiSelectIds);
const len = this.multiSelectIds.length;
if (len === 0) {
this.selectAllState = 'unchecked';
} else if (len > 0 && len < this.options.records.length) {
this.selectAllState = 'indeterminate';
} else {
this.selectAllState = 'checked';
}
}
public onSelectAllChange(checkedState: SelectAllCheckboxState) {
this.multiSelectAllCurrentPage();
if (this.multiSelectIds.length > 0) {
this.selectAllState = 'checked';
} else {
this.selectAllState = 'unchecked';
}
}
public kendoPageChange(event: PageChangeEvent): void {
this.kendoGridPageDataSkip = event.skip;
const pageSize = event.take;
if (this.kendoGridPageDataSkip === 0) {
this.options.page = 1;
} else {
this.options.page = (this.kendoGridPageDataSkip / pageSize) + 1;
}
const pageEvent = { pageIndex: this.options.page, pageSize: pageSize };
this.options.paginateFunction(pageEvent);
}
public isSearchableProperty(property) {
return property &&
property.propertyType === PropertyType.string &&
!property.prohibited &&
this.options &&
this.options.filterListFunction &&
typeof this.options.filterListFunction === 'function';
}
public applyFilter(event: any) {
this.filter = event;
this.searchParams = {
Criteria: [],
AdvancedConditions: ''
};
if (!event.filters || event.filters == null || event.filters.count === 0) {
return;
}
let filters: any;
let key: string;
let value: string;
let operator: string;
const conjunction = 'AND';
event.filters.forEach(filter => {
key = this.getKendoFieldName(filter.field);
value = filter.value;
operator = filter.operator;
if (operator === 'contains') {
value = '*' + value + '*';
}
filters = Map([[key, value]]);
const newSearchParams = this.helper.createSearchParams(filters, conjunction);
this.searchParams.Criteria = this.listService.mergeCriteria(this.searchParams.Criteria, newSearchParams.Criteria);
this.searchParams.AdvancedConditions = this.searchParams.Criteria.map((r, index) => {
return index + 1;
}).join(' ' + conjunction + ' ');
});
this.onListFilterSearch();
}
}
与附加参数matrix()
和字符向量NROW
的长度结合使用,以定义零矩阵的行数和列数。该函数利用回收属性并将矩阵元素填充为零。
第二步,正如您所说的,将零矩阵(X)与另一个(Y)矩阵与column_list
合并为Z矩阵。 必须考虑以下假设: Y具有相同的行数,并且Y的列具有不同的名称(以正确标识过程)。然后,您只需重新排序带有方括号的矩阵和基于新矩阵(Z)的列名的函数cbind
。
order()
答案 1 :(得分:0)
您只需要创建新的数据框,然后绑定,然后对列进行重新排序。为此,您可以在列名称的向量上使用sort()
函数,并将输出分配给向量。然后,您可以根据定义的列向量对数据框进行子集化,以对列进行重新排序
missing_letters <- data.frame(
C = rep(0, 3), # N = 3 in this example
F = rep(0, 3),
G = rep(0, 3),
M = rep(0, 3),
O = rep(0, 3),
Y = rep(0, 3),
Z = rep(0, 3)
)
your_letters <- data.frame(
A = c(.1, 0, .1),
B = c(.2, .2, 0),
D = c(.1, .3, .1),
E = c(.5, 0, .1),
H = c(.1, 0, 0),
I = c(.1, .2, .3)
)
binded_letters <- cbind(your_letters, missing_letters)
alphabetical_order <- sort(colnames(binded_letters))
final_data <- binded_letters[, alphabetical_order]
final_data
#> A B C D E F G H I M O Y Z
#> 1 0.1 0.2 0 0.1 0.5 0 0 0.1 0.1 0 0 0 0
#> 2 0.0 0.2 0 0.3 0.0 0 0 0.0 0.2 0 0 0 0
#> 3 0.1 0.0 0 0.1 0.1 0 0 0.0 0.3 0 0 0 0