我的数据框如下
X Y Z
A *
B
C *
D
E
F *
G *
H *
I * *
我想将列名更改为行,以使其与原始行重复该单元格中出现星号的次数
结果显示如下
School Agency
X A
X C
X F
X G
X I
Y I
Z *
我经历了this post,但是它具有相同的行名和列名,所以行不通。
答案 0 :(得分:2)
我们可以使用逻辑arr.ind
上which
中的matrix
中的i1 <- which(dat == "*", arr.ind = TRUE)
data.frame(School = colnames(dat)[i1[,2]], Agency = row.names(dat)[i1[,1]])
获取行/列索引,并获取相应的行名和列名
dat <- structure(list(X = c("*", "", "*", "", "", "*", "*", "", "*"),
Y = c("", "", "", "", "", "", "", "", "*"), Z = c("", "",
"", "", "", "", "", "*", "")), row.names = c("A", "B", "C",
"D", "E", "F", "G", "H", "I"), class = "data.frame")
$quarters = $collection->where('fundamental.fiscal_period', '!=', 'FY');
// use `groupBy()` to organize the quarters into the right chunks
$grouped = $quarters->groupBy(function($item) {
// concatenate the company name and fiscal year to create the "group" name
return $item->company->name.'_'.$item->fundamental->fiscal_year;
});
// use `$fiscalYears` with `map()` and `flip()` to create a collection
// with the same key structure as $grouped
$filter = $fiscalYears->map(function($item) {
return $item->company->name.'_'.$item->fundamental->fiscal_year;
})->flip();
// filter the collection with `intersectByKeys()`
$result = $grouped->intersectByKeys($filter);
// If you want, replace the keys with numeric indices and convert to array
$result = $result->values()->toArray();