在 R 中拆分后如何重新组合值?

How to recombine values after a split in R?

我有一个数据变量 X,我已对其执行以下操作

Xnew = split(X$col1,list(X$col3,X$col4))
S = sapply(Xnew,mean)

我现在有一个向量,其中每个元素都可以通过

访问
S['SomeValCol3.SomeValCol4']

现在我想创建一个向量,其中包含的列等于 col3 中唯一值的数量,并且将 col4 添加为索引每个值的列向量。也就是说,

第 4 列 | Col3[1]| Col3[2] |.... Col4[0]| S['SomeValCol3.SomeValCol4'] | ... . . .

等等。

举个例子,假设我有以下向量

S['v31.v41'] = 0.5
S['v32.v41'] = 0.25
S['v33.v41'] = 0.35
S['v31.v42'] = 0.5
S['v32.v42'] = 0.25
S['v33.v42'] = 0.35
S['v31.v43'] = 0.5
S['v32.v43'] = 0.25
S['v33.v43'] = 0.35

我从拆分中得到的,然后我想要这个矩阵

V4 | V31 | V32 | V33
V41  0.5   0.25  035
V42  0.5   0.25  035
V43  0.5   0.25  035

使用 reshape2 库我首先 melt 向量 S 到 data.frame 并添加 row/column 变量名字

library(reshape2)
S.melted <- melt(S)
S.melted$v1 <- gsub('\.v[[:digit:]]+', '', rownames(S.melted))
S.melted$v2 <- gsub('\v[[:digit:]]+\.', '', rownames(S.melted))

这给我 S.melted 格式如下:

        value v1  v2
v31.v41  0.50 v31 v41
v32.v41  0.25 v32 v41
...

然后使用 acast

获取首选格式
> acast(S.melted, v1 ~ v2)
    v41  v42  v43
v31 0.50 0.50 0.50
v32 0.25 0.25 0.25
v33 0.35 0.35 0.35

使用base R

 xtabs(values~V1+V2, transform(stack(S), V2=sub('\..*', '', ind),
                  V1=sub('.*\.', '', ind)))
 #        V2
 #V1    v31  v32  v33
 # v41 0.50 0.25 0.35
 # v42 0.50 0.25 0.35
 # v43 0.50 0.25 0.35

数据

 S <- structure(c(0.5, 0.25, 0.35, 0.5, 0.25, 0.35, 0.5, 0.25, 0.35
 ), .Names = c("v31.v41", "v32.v41", "v33.v41", "v31.v42", "v32.v42", 
 "v33.v42", "v31.v43", "v32.v43", "v33.v43"))