然后在他提供的例子里引掉 tMatrix[i,j, ] <- testVec
,可以跑成功,就是上诉的第二步。
因为 i 和 j 都是从 names
里附值,而 names = c("AA", "Aa", "aa")
,所以先把tMatrix[i,j, ]
的格式弄清楚。于是把 tMatrix[i,j, ]
换成是 tMatrix["AA","Aa", ]
:
> tMatrix["AA","Aa", ]
AA Aa aa
0 0 0
这里我刚开始怀疑的是tMatrix[i,j, ]
里的 i 和 j 换成别的格式(object 名)会不会一样,于是:
> tMatrix["aa","aa", ]
AA Aa aa
0 0 0
因为 tMatrix[i,j, ] <- testVec
, 从这里可以看出 testVec
必须是这个格式 (数值可以任意):
AA Aa aa
0 0 0
这里我当时绕了点弯路,当时凭直觉想的是会不会是testVec
有小于或者大于3的元素,因为error message说的是不匹配,于是我把 testVec
写成是4个元素的例子,error message重现:
> testVec <- setNames(object = numeric(4), nm =c("AA","AA", "Aa","aa") )
> tMatrix["Aa","aa", ] <- testVec
Error in tMatrix["Aa", "aa", ] <- testVec :
number of items to replace is not a multiple of replacement length
然后绕了会发现testVec <- setNames(object = numeric(size), nm = names)
已经hard code是3个元素了。于是怀疑到元素名。
往上推,这里是给testVec
附值的过程:
for (k in ij_prod)
{
testVec[k] <- testVec[k]+5
}
这里要依赖于ij_prod
,就怀疑到 ij_prod
头上。
为了先把ij_prod
弄清楚是什么,用实值代替 i 和 j,如下:
> j_name <- strsplit("AA", split='')[[1]]
> i_name <- strsplit("Aa", split='')[[1]]
> ij_prod <- as.vector( outer(j_name, i_name, paste0, sep='') )
> ij_prod
[1] "AA" "AA" "Aa" "Aa"
然后再跑 sort 的部分:
> ij_prod <- vapply( strsplit(ij_prod, split=''),
+ function(x) {paste0(
+ # x,
+ sort(x, decreasing=TRUE),
+ collapse='')},
+ FUN.VALUE = character(1))
> ij_prod
[1] "AA" "AA" "Aa" "Aa"
发现结果是一样的,于是怀疑人生了一会。好在我贼心不死,于是换个实值试试。结果发现:
j_name <- strsplit("aa", split='')[[1]]
i_name <- strsplit("Aa", split='')[[1]]
ij_prod <- as.vector( outer(j_name, i_name, paste0, sep='') )
> ij_prod
[1] "aA" "aA" "aa" "aa"
如果跑 sort 的部分后:
> ij_prod <- vapply( strsplit(ij_prod, split=''),
+ function(x) {paste0(
+ # x,
+ sort(x, decreasing=TRUE),
+ collapse='')},
+ FUN.VALUE = character(1))
> ij_prod
[1] "Aa" "Aa" "aa" "aa"
所以说 sort 这部分是有必要的,如果用这个实值没有 sort 的话,就会重现一样的 error message:
> j_name <- strsplit("aa", split='')[[1]]
> i_name <- strsplit("Aa", split='')[[1]]
> ij_prod <- as.vector( outer(j_name, i_name, paste0, sep='') )
> for (k in ij_prod)
+ {
+ testVec[k] <- testVec[k]+5
+ }
> tMatrix["Aa","aa", ] <- testVec
Error in tMatrix["Aa", "aa", ] <- testVec :
number of items to replace is not a multiple of replacement length
于是就怀疑到 sort 头上了,由于这里 sort 的不是数值,是 character vector,这就涉及到大小写和字母排列孰轻孰重的问题。于是搜的关键词是: sort(), character, R。 然后SO上有,各路贴子上也用很多。https://stackoverflow.com/questions/7229408/what-are-the-r-sorting-rules-of-character-vectors 等等。
于是我就看了你的答案。。。。。。如果你没贴答案的话我会换个 locales 看看能不能跑通。