Non character argument in R string split function (strsplit)

AWE picture AWE · Mar 15, 2013 · Viewed 77.8k times · Source

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)

Answer

AWE picture AWE · Mar 15, 2013

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)
}