I'm iterating over a vector, for each element I look something up in a table by rowname and copy the return into a different vector. The following code is used for that
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)
}
All it spits out is a vector with numbers....while all other variables seems to contain the correct information (as checked by the print function) I have the feeling I'm doing something terribly wrong in filling the output vector... I could also use
output <- c(output,toappend)
But that gives me exactly the same, wrong and strange output.
All help is very much appreciated!
Output example
> 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"
Very likely you're using a data frame and not a table, and as likely your third column is not a character vector but a factor. And there is no need to write that function, you could easily obtain the wanted by:
conditions[X,3]
with X being a character vector of row names. eg :
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
To get it in characters:
> as.character(X[test,3])
[1] "f" "d" "a"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With