I am trying to increase the value of all the numbers in a table similar to the one below. Is there any way to do this in R? I am aware this is a very simple task in python.
if(!require(tidyverse)){install.packages("tidyverse");library('tidyverse')}
Gene = sprintf("Gene_%s", rep(10:39))
Cell = sprintf("Cell_%s", rep(10:19))
mat <- matrix(rnorm(10), ncol = 10, nrow = 30)
df <- as.data.frame(mat)
colnames(df) <- Cell
row.names(df) <- Gene
df <- rownames_to_column(df,var = "Gene")
df
I have tried df 1
and get an error:
Error in FUN(left, right): non-numeric argument to binary operator
Traceback:
1. Ops.data.frame(df, 1)
2. eval(f)
3. eval(f)
My desired output is something like this...
example <- df$Cell_10 1
example
However I need to do this for the whole dataframe
CodePudding user response:
The first column is character
.
> str(df)
'data.frame': 30 obs. of 11 variables:
$ Gene : chr "Gene_10" "Gene_11" "Gene_12" "Gene_13" ...
$ Cell_10: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_11: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_12: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_13: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_14: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_15: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_16: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_17: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_18: num 0.409 1.689 1.587 -0.331 -2.285 ...
$ Cell_19: num 0.409 1.689 1.587 -0.331 -2.285 ...
So, exclude that while adding
df[-1] <- df[-1] 1
Or programmatically find the index of numeric columns
i1 <- which(sapply(df, is.numeric))
df[i1] <- df[i1] 1
Or in tidyverse
, we can check the column type while adding
library(dplyr)
df <- df %>%
mutate(across(where(is.numeric), ~ .x 1))