[R] replace string values with numbers

arun smartpink111 at yahoo.com
Thu Sep 27 01:28:29 CEST 2012


Hi,

You can also try these:

Gene<-read.table(text="
P1 P2 P3
 CG CG GG
-- --  AC
 -- AC CC
AC  --  AC
",header=TRUE,sep="")
Gene<-sapply(Gene,as.character)
Gene<-data.frame(gsub("GG","3",Gene))
 Gene
#  P1 P2 P3
#1 CG CG  3
#2 -- -- AC
#3 -- AC CC
#4 AC -- AC
# str(Gene)
#'data.frame':    4 obs. of  3 variables:
# $ P1: Factor w/ 3 levels "--","AC","CG": 3 1 1 2
#$ P2: Factor w/ 3 levels "--","AC","CG": 3 1 2 1
# $ P3: Factor w/ 3 levels "3","AC","CC": 1 2 3 2


#2nd way 
Gene<-read.table(text="
P1 P2 P3
 CG CG GG
-- --  AC
 -- AC CC
AC  --  AC
",header=TRUE,sep="")

 Gene<-within(Gene,{P1<-as.character(P1);P2<-as.character(P2);P3<-as.character(P3)})
Gene[sapply(Gene,function(x) grepl("GG",x))]<-3
Gene
  P1 P2 P3
#1 CG CG  3
#2 -- -- AC
#3 -- AC CC
#4 AC -- AC
 str(Gene)
#'data.frame':    4 obs. of  3 variables:
# $ P1: chr  "CG" "--" "--" "AC"
# $ P2: chr  "CG" "--" "AC" "--"
# $ P3: chr  "3" "AC" "CC" "AC"

A.K.

----- Original Message -----
From: JiangZhengyu <zhyjiang2006 at hotmail.com>
To: r-help at r-project.org
Cc: 
Sent: Wednesday, September 26, 2012 3:52 PM
Subject: [R] replace string values with numbers





Hi everyone, I have a data frame Gene with SNPs eg.   P1 P2 P3 
CG CG GG
-- --  AC 
-- AC CC
AC  --  AC I tried to replace all the GG with a value 3.    Gene[Gene=="GG"]<-3 It always give me:  Warning in `[<-.factor`(`*tmp*`, thisvar, value = 3) :
  invalid factor level, NAs generated Does any know if there is anything wrong with my code? Thanks, Zhengyu                           
    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.





More information about the R-help mailing list