R: for loop with library (data.table)
Hi R users !
I am using library(data.table) and I would like to do a for loop that calculates the mean of columns 1:4, based on col5 values.
colnames(DT) # "col1" "col2" "col3" "col4" "col5"
for (i in 1:4)
{
o=colnames(DT)[[i]]
l=DT[,mean(o), by=col5]
print(l)
}
The problem is that DT does not take colnames as character vectors ("col")..
Any suggestion is appreciated.
Best !
Kizuna
• 747 views
•
link
1 answer
One way to handle this would be to use subset(). Directly from the manual:
The subset argument works on the rows and will be evaluated in the data.table so columns can be referred to (by name) as variables in the expression. The data.table that is returned will maintain the original keys as long as they are not selected out.
Subset the table to what you want, then calculate the mean.
• 0 views
•
link
Log in to answer this question.
Hello Kizuna!
We believe that this post does not fit the main topic of this site.
This seems to be a pure R programming question; unless you make the connection to bioinformatics very clear (better than "oh yeah, then my row-names are some genes") this content is regarded as off-topic.
For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.
If you disagree please tell us why in a reply below, we'll be happy to talk about it.
Cheers!