我正在嘗試增加類似于下表的表格中所有數字的值。有沒有辦法在 R 中做到這一點?我知道這是 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
我試過df 1并得到一個錯誤:
Error in FUN(left, right): non-numeric argument to binary operator
Traceback:
1. Ops.data.frame(df, 1)
2. eval(f)
3. eval(f)
我想要的輸出是這樣的......
example <- df$Cell_10 1
example
但是我需要為整個資料框執行此操作
uj5u.com熱心網友回復:
第一列是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 ...
所以,在添加時排除它
df[-1] <- df[-1] 1
或以編程方式查找數字列的索引
i1 <- which(sapply(df, is.numeric))
df[i1] <- df[i1] 1
或者tidyverse,我們可以在添加時檢查列型別
library(dplyr)
df <- df %>%
mutate(across(where(is.numeric), ~ .x 1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452986.html
下一篇:無法切片numpy陣列輸入
