34

This works

x <- "0.466:1.187:2.216:1.196"
y <- as.numeric(unlist(strsplit(x, ":")))

Values of blat$LRwAvg all look like X above but this doesn't work

for (i in 1:50){
  y <- as.numeric(unlist(strsplit(blat$LRwAvg[i], "\\:")))
  blat$meanLRwAvg[i]=mean(y)
}

Because of:

Error in strsplit(blat$LRwAvg[i], "\:") : non-character argument

It doesn't matter if I have one, two or null backslashes.

What's my problem? (Not generally, I mean in this special task, technically)

mnel
  • 113,303
  • 27
  • 265
  • 254
AWE
  • 4,045
  • 9
  • 33
  • 42
  • What is the output of `class(blat$LRwAvg)`, and can you give us some data from `blat$LRwAvg` – alexwhan Mar 15 '13 at 10:32
  • 4
    @AWE It is an error type. coerce the argument to character , `as.character(blat$LRwAvg)` – agstudy Mar 15 '13 at 10:36
  • 1
    @alexwhan I noticed that so deleted my comment, but not quickly enough :$. It looks like its a problem with factors. So coerce to character as @agstudy suggests, or use `stringsAsFactors=FALSE` when creating the data.frame. – James Mar 15 '13 at 10:44
  • @alexwhan, class(blat$LRwAvg) = factor, @agstudy, `blat$LRwAvg <- as.character(blat$LRwAvg)` before loop fixed it! – AWE Mar 15 '13 at 10:46
  • @AWE you can answer and accept your own question. – Paul Hiemstra Mar 15 '13 at 10:48
  • Isn't it more appropriate that agstudy answers it so I can accept? – AWE Mar 15 '13 at 10:51
  • @AWE it doesn't matter. It is even encouraged to answer his own question. So answer and accept it please. – agstudy Mar 15 '13 at 10:54

1 Answers1

37

As agstudy implied blat$LRwAvg <- as.character(blat$LRwAvg) before loop fixed it

blat$meanLRwAvg <- blat$gtFrqAvg #or some other variable in data frame with equal length
blat$LRwAvg <- as.character(blat$LRwAvg)
for (i in 1:50){
  y <- as.numeric(unlist(strsplit(blat$LRwAvg[i], "\\:")))
  blat$meanLRwAvg[i]=mean(y)
}
AWE
  • 4,045
  • 9
  • 33
  • 42