我正在迭代一个向量,对于每个元素,我通过rowname在表中查找某些内容并将返回值复制到另一个向量中.以下代码用于此
gs1 = function(p)
{
output <- character() #empty vector to which results will be forwarded
for (i in 1:length(p)) {
test <- p[i]
index <- which(rownames(conditions) == test)
toappend <- conditions[index,3] #working
output[i] <- toappend
print(paste(p[i],index,toappend,output[i]))
}
return(output)
}
Run Code Online (Sandbox Code Playgroud)
所有它吐出来的是带有数字的向量....而所有其他变量似乎都包含正确的信息(由打印函数检查)我感觉我在填充输出向量时做了一些非常错误的事情......我也可以用
output <- c(output,toappend)
Run Code Online (Sandbox Code Playgroud)
但这给了我完全相同,错误和奇怪的输出.
非常感谢所有帮助!
输出示例
> gs1 = function(p)
+ {
+ output <- character() #empty vector to which results will be pasted
+
+ for (i in 1:length(p)) {
+ test <- p[i]
+ index <- which(rownames(conditions) == test)
+ toappend <- conditions[index,3] #working
+
+ output <- c(output,toappend)
+ output[i] <- toappend
+ print(paste(p[i],index,toappend,output[i],sep=","))
+ }
+ return(output)
+ }
> ###########################
> test <- colnames(tri.data.1)
> gs1(test)
[1] "Row.names,,,NA"
[1] "GSM235482,1,Glc A,5"
[1] "GSM235484,2,Glc A,5"
[1] "GSM235485,3,Glc A,5"
[1] "GSM235487,4,Xyl A,21"
[1] "GSM235489,5,Xyl A,21"
[1] "GSM235491,6,Xyl A,21"
[1] "GSM297399,7,pH 2.5,12"
[1] "GSM297400,8,pH 2.5,12"
[1] "GSM297401,9,pH 2.5,12"
[1] "GSM297402,10,pH 4.5,13"
[1] "GSM297403,11,pH 4.5,13"
[1] "GSM297404,12,pH 4.5,13"
[1] "GSM297563,13,pH 6.0,14"
[1] "GSM297564,14,pH 6.0,14"
[1] "GSM297565,15,pH 6.0,14"
[1] "5" "5" "5" "5" "21" "21" "21" "12" "12" "12" "13" "13" "13" "14" "14" "14"
Run Code Online (Sandbox Code Playgroud)
很可能你使用的是数据框而不是表格,因为你的第三列可能不是字符向量而是一个因素.并且没有必要编写该函数,您可以通过以下方式轻松获得所需的函数:
conditions[X,3]
Run Code Online (Sandbox Code Playgroud)
X是行名的字符向量.例如:
X <- data.frame(
var1 = 1:10,
var2 = 10:1,
var3 = letters[1:10],
row.names=LETTERS[1:10]
)
> test <- c("F","D","A")
> X[test,3]
[1] f d a
Levels: a b c d e f g h i j
Run Code Online (Sandbox Code Playgroud)
要获得字符:
> as.character(X[test,3])
[1] "f" "d" "a"
Run Code Online (Sandbox Code Playgroud)