我发现合并一个困难的概念(内,外,右,左 ......)原谅这个简单化的问题。
我想将生成的每个列合并到之前的列。
labelA <- array(letters[1:10], dim=c(10,1))
## Function: test_values ##
test_func = function(df, nameA, nameB) {
test_values <- array(data=1, dim=c(10,1))
for (i in 1:10){
test_values[i] <- paste(nameA, nameB, i, sep="_")
}
merge (x=df, y=test_values, sort=FALSE, all=TRUE) # ??
}
# Comparison #1
nameA <-"A"
nameB <-"B"
gran_total = test_func(labelA, nameA, nameB)
# Comparison #2
nameA <-"C"
nameB <-"D"
gran_total = test_func(gran_total, nameA, nameB)
但我的输出是 30行1列的矩阵。
但 我想要 (无法弄清楚如何返回) 10行3列
的矩阵V1 V2 V3
a A_B_1 C_D_1
b A_B_2 C_D_2
c A_B_3 C_D_3
d A_B_4 C_D_4
e A_B_5 C_D_5
...
答案 0 :(得分:2)
您所需要的可能是cbind
或data.frame
而不是merge
。
以下是一个例子:
> labelA <- array(letters[1:3], dim=c(3,1))
> # simple way
> data.frame(labelA, paste("A", "B", 1:3, sep = "_"), paste("C", "D", 1:3, sep = "_"))
labelA paste..A....B...1.3..sep...._.. paste..C....D...1.3..sep...._..
1 a A_B_1 C_D_1
2 b A_B_2 C_D_2
3 c A_B_3 C_D_3
> # generalize as a function
> f <- function(df, nA, nB) paste(nA, nB, 1:nrow(df), sep = "_")
> data.frame(labelA, f(labelA, "A", "B"), f(labelA, "C", "D"))
labelA f.labelA...A....B.. f.labelA...C....D..
1 a A_B_1 C_D_1
2 b A_B_2 C_D_2
3 c A_B_3 C_D_3
> # more generalize for flexible arguments
> f2 <- function(df, labels)
+ data.frame(df, do.call("cbind", llply(labels,
+ function(x) do.call("paste", c(as.list(x), list(1:nrow(df)), sep = "_")))))
> f2(labelA, list(c("A", "B"), c("C", "D")))
df X1 X2
1 a A_B_1 C_D_1
2 b A_B_2 C_D_2
3 c A_B_3 C_D_3
> f2(labelA, list(c("A", "B"), c("C", "D"), c("E", "F", "G")))
df X1 X2 X3
1 a A_B_1 C_D_1 E_F_G_1
2 b A_B_2 C_D_2 E_F_G_2
3 c A_B_3 C_D_3 E_F_G_3