gpt4 book ai didi

使用 for 循环填充向量的 R 问题

转载 作者:行者123 更新时间:2023-12-04 23:09:21 37 4
gpt4 key购买 nike

我正在迭代一个向量,对于每个元素,我按行名在表中查找某些内容并将返回值复制到不同的向量中。以下代码用于

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)
}

它吐出的只是一个带有数字的向量......而所有其他变量似乎都包含正确的信息(由打印函数检查)
我觉得我在填充输出向量时做错了什么......我也可以使用
output <- c(output,toappend)

但这给了我完全相同、错误和奇怪的输出。

非常感谢所有帮助!

输出示例
> 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"

最佳答案

很可能您使用的是数据框而不是表格,并且您的第三列很可能不是字符向量而是一个因子。并且无需编写该函数,您可以通过以下方式轻松获得所需的内容:

conditions[X,3]

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

要以字符形式获取它:
> as.character(X[test,3])
[1] "f" "d" "a"

关于使用 for 循环填充向量的 R 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4460275/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com