Skip to content
Prev 206109 / 398503 Next

apply a function down each column

Laetitia,

I was just responding to your comment that "R complains
about a syntax error". But I realize now that "2x" would
probably cause an "unexpected symbol" error.

Here's what I get when I run your loop; what do you get?

 > for (x in 1:(nrow(dat)-1)) {
+  a <- as.character(dat[(2x-1),1])
Error: unexpected symbol in:
"for (x in 1:(nrow(dat)-1)) {
  a <- as.character(dat[(2x"
 >  b <- as.character(dat[(2x),1])
Error: unexpected symbol in " b <- as.character(dat[(2x"
 >  lettermatch(a,b)
Error in strsplit(a, "") : object 'a' not found
 > }
Error: unexpected '}' in "}"
 >

and here's what I get when I fix the obvious syntax
error:

 > for (x in 1:(nrow(dat)-1)) {
+  a <- as.character(dat[(2*x-1),1])
+  b <- as.character(dat[(2*x),1])
+  lettermatch(a,b)
+ }
Error in fix.by(by.x, x) : 'by' must specify valid column(s)
 >

That leaves two problems:
1) you're looking at the wrong column in dat[,1]; that
    should be dat[,2], etc.
2) that error message indicates that your index variable (x)
    gets to invalid values.

Try this:

for (x in 1:(nrow(dat)/2)) {
  a <- dat[(2*x-1),2]  # odd rows
  b <- dat[(2*x),2]    # even rows
  print(lettermatch(a,b))
}

You don't need the as.character() if you have character data.
Always do a str(dat) before you do any analysis.

  -Peter Ehlers
Laetitia Schmid wrote: