替换 R 中的值 - 收到错误 [英] Replacing Values in R - Error Received
问题描述
所以我有一个填充核苷酸信息的数据框(称为 gen):每个值是 A、C、G 或 T.我希望用 1 替换 A,用 2 替换 C,用 3 替换 G,和 T与 4. 当我使用函数 gen[gen==A] = 1
时,出现错误:
So I have a data frame (called gen) filled with nucleotide information: each value is either A, C, G, or T. I am looking to replace A with 1, C with 2, G with 3, and T with 4. When I use the function gen[gen==A] = 1
, I get the error:
[<-.data.frame
(*tmp*
, gen == A, value = 1) 中的错误:未找到对象A"
Error in [<-.data.frame
(*tmp*
, gen == A, value = 1) :
object 'A' not found
我什至尝试使用 gen <- replace(gen, gen == A, 1)
,但它给了我同样的错误.有谁知道如何解决这个错误?如果没有,是否可以在 R 中安装一个程序包,该程序包可以将 A、C、G 和 T 转换为数值?
I even tried using gen <- replace(gen, gen == A, 1)
, but it gives me the same error. Does anyone know how to fix this error? If not, is there a package that I can install in R with a program that will convert A, C, G, and T to numeric values?
谢谢
推荐答案
您需要将 A 用引号括起来,否则 R 会查找名为 A 的变量.如果列是字符向量:
You need to wrap A in quotes or else R looks for a variable named A. If the columns are character vectors:
R> gen = data.frame(x = sample(c("A", "C", "G", "T"), 10, replace = TRUE), y = sample(c("A", "C", "G", "T"), 10, replace= TRUE), stringsAsFactors = FALSE)
R> gen[gen == "A"] = 1
R> gen
x y
1 1 1
2 C C
3 G T
4 T T
5 G G
6 G G
7 1 1
8 C C
9 T 1
10 1 1
也是一种一次性完成的方法
also 1 way to do all at once
R> library(car)
R> sapply(gen, recode, recodes = "'A'=1; 'C'=2; 'G'=3; 'T'=4")
x y
[1,] 1 1
[2,] 2 2
[3,] 3 4
[4,] 4 4
[5,] 3 3
[6,] 3 3
[7,] 1 1
[8,] 2 2
[9,] 4 1
[10,] 1 1
如果列是因子
R> gen = data.frame(x = sample(c("A", "C", "G", "T"), 10, replace = TRUE), y = sample(c("A", "C", "G", "T"), 10, replace= TRUE))
R> sapply(gen, as.numeric)
x y
[1,] 1 1
[2,] 2 4
[3,] 1 2
[4,] 4 1
[5,] 2 2
[6,] 1 4
[7,] 4 3
[8,] 3 3
[9,] 2 4
[10,] 4 2
这篇关于替换 R 中的值 - 收到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!