给出以下数据集:
Ind <- c(rep("deima1",5), rep("deima2", 5), rep("eryt1", 5), rep("eryt2",5))
Sp <- c(rep("P. deimaticus",10), rep("P. erythros", 10))
Groups <- data.frame(Ind, Sp)
对于Groups$Ind
的每个级别,我想从Groups$Sp
获取相应的物种,并将其存储在一系列因子中。结果的长度应为levels(Groups$Ind)
。
> result
[1] "P. deimaticus" "P. deimaticus" "P. erythros" "P. erythros"
这个问题在我看来似乎很简单,但是我无法想到任何可以解决问题的功能。我尝试了几种不同的循环方式,但似乎缺少了一些东西。
答案 0 :(得分:1)
这是你想要的吗?
let initial = [{code:"1",size: 0},{code:"2",size: 0},{code:"3",size: 0},{code:"4",size: 0}];
let update = [{code:"1",size: 100},{code:"2",size: 100},{code:"2",size: 120}];
let res = initial.map(({code, size}, index) =>
({code, size: size
// get elements having same `"code"` property value from `update` array
// add the result
+ update.filter(({code:c}) => code === c)
.reduce((n, {size:s}) => n+= s, 0)})
);
console.log(res);
或者您可能希望将信息存储在数据框中。
lapply(split(Groups, Groups$Ind), function(x) unique(as.character(x[["Sp"]])))
$deima1
[1] "P. deimaticus"
$deima2
[1] "P. deimaticus"
$eryt1
[1] "P. erythros"
$eryt2
[1] "P. erythros"
答案 1 :(得分:0)
您可以使用rep
Ind <- c(rep("deima1",5), rep("deima2", 5), rep("eryt1", 5), rep("eryt2",5))
Sp <- c(rep("P. deimaticus",10), rep("P. erythros", 10))
Groups <- data.frame(Ind, Sp)
Grp_sp <- levels(Groups$Sp)
rep(Grp_sp, length.out = length(levels(Groups$Ind)) )