开发者

Error in for loop in r

I am working with a data frame called bumpus. When I try to select only certain rows using for and if statements I get an error:

Error: unexpected '{' in "for(i in 1:(nrow(bumpus)){" 

Could you please help me to figure out what is it that I am missing? Here is my for loop:

fo开发者_运维问答r(i in 1:(nrow(bumpus)) {
    if(bumpus[i,2]=="m")
    {
    bumpus_males<-bumpus[i,]
    }
}


Count your parentheses (or use a good editor that helps with matching).

You have 3 openening parens, then only 2 closing before the 1st brace ({), you need one more closing paren before the brace to match the one for the for condition.

Also, you can do this much simpler with the ifelse function and not need the loop.


Greg solved your problem, but your code still looks funny. As written (with Greg's correction), your loop will work through each row, and if the row has "m" in the second column, it will replace bumpus_males with just that row. So if more than one row has "m" in the second column, you'll only get the last row saved as bumpus_males. I suspect what you really want here is more like:

bumpus_males <- subset(bumpus, bumpus[,2] == "m")

This will create a new data.frame with all the rows where column 2 is "m".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜