本文介绍了R将整个数据帧中的字母转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我无法在数据框的所有列上应用 chartr()函数,以将字母转换为数字。 $ b $我管理在单列上进行管理,但我希望能够在整个数据框架上执行此操作。以下是我的数据示例: ID = c(1,2,3) POS1 = c 'AG','GC','TT') POS2 = c('GT','CC','TC') POS3 = c('GG','CT' ') DF = data.frame(ID,POS1,POS2,POS3) DF $ POS1X< - chartr('ACGT','1234',DF $ POS1) ID POS1 POS2 POS3 POS1X 1 1 AG GT GG 13 2 2 GC CC CT 32 3 3 TT TC AT 44 从代码中可以看出,我要将A转换为1,将C转换为2,将G转换为3,将T转换为4.我有40 +列,因此重复与上述相同的命令40+次将是不切实际的(特别是如果我遇到相同的问题后来说几百列) ykl 解决方案为什么不使用 lapply ? DF2 DF2 [-1]< - lapply(DF2 [-1],chartr,old =ACGT,new =1234) DF2 #ID POS1 POS2 POS3 #1 1 13 34 33 #2 2 32 22 24 #3 3 44 42 14 / pre> 现在,您有两个具有等效列名称的数据帧,我发现比将旧列添加到旧数据更容易进行比较。特别是当有很多列时。 I am having trouble applying the chartr() function on all columns of my data frame for converting letters to numbers.I managed doing it on single columns, yet I want to be able to do it on the entire data frame. Here is an example of my data:ID = c(1,2,3)POS1 = c('AG','GC','TT')POS2 = c('GT','CC','TC')POS3 = c('GG','CT','AT')DF = data.frame(ID,POS1,POS2,POS3)DF$POS1X <- chartr('ACGT','1234',DF$POS1) ID POS1 POS2 POS3 POS1X1 1 AG GT GG 132 2 GC CC CT 323 3 TT TC AT 44As seen from the code, I want to convert A to 1, C to 2, G to 3, and T to 4. I have 40+ columns and thus repeating the same command as above 40+ times would be impractical (especially if I run into the same problem later on with say hundreds of columns)Sincerily,ykl 解决方案 Why not use lapply?DF2 <- DF ## to not overwrite the original DFDF2[-1] <- lapply(DF2[-1], chartr, old = "ACGT", new = "1234")DF2# ID POS1 POS2 POS3# 1 1 13 34 33# 2 2 32 22 24# 3 3 44 42 14Now you have two data frames with equivalent column names which I find easier to compare than appending new columns to the old data. Especially when there are many many columns. 这篇关于R将整个数据帧中的字母转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-15 08:29