0
$\begingroup$

lets say I have the following dataframe:

Ensembl_ID          A   B   C   D   E   F   G
ENSG00000236601.2   0   0   0   1   0   0   1
ENSG00000237094.12  2   187 442 109 88  144 486
ENSG00000269732.1   0   0   0   0   0   0   0
ENSG00000284733.1   0   0   0   0   0   0   0
ENSG00000233653.3   0   0   0   0   0   0   0
ENSG00000250575.1   1   11  17  5   5   8   17
ENSG00000278757.1   0   0   2   0   1   0   7
ENSG00000230021.9   0   25  30  27  9   8   11
ENSG00000235146.2   0   0   0   0   0   0   0
ENSG00000225972.1   0   7   3016    11  5   14  5
ENSG00000225630.1   1   113 194 76  91  47  94
ENSG00000237973.1   25  1037    9767    1160    886 1321    5220

What I would like to do is only keep the ~top 50 highly variable genes:

I thought it would be like this: dif_genes <- order(apply(df, 1, var), decreasing=TRUE)[1:50] but that leaves me with a vector containing variances without genes.

$\endgroup$

1 Answer 1

3
$\begingroup$

One way is adding a new var column to your original data frame and sorting the updated data frame by the newly introduced column:

df$var <- apply(df, 1, var)
df[order(df$var, decreasing=TRUE),] 
$\endgroup$
1
  • $\begingroup$ the OP wants top 50. I would suggest df[order(apply(df[, -1], 1, var), decreasing=TRUE),][1:50, ] to avoid adding the variance as a sample (in case OP wants to do a heatmap) and removing the names that seem to be in the first column. The key @user16197 to keep the top 50 genes is the comma after the 50; it tells R that this is a 2D data. $\endgroup$
    – llrs
    Sep 27, 2022 at 22:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.