Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

loops - Conditional Counter In New Column - R

I'd like help creating a function or loop that adds a value to a new column based on values in the same row of other columns. The goal is to create a kind of scoring system for a survey dataset.

Here's a sample dataframe

dfp <- data.frame(id=c("resp1", "resp2", "resp3"), 
                 cat1=c("gov", "biz", "biz"), 
                 cat2=c("dem", "gop", "dem"),
                 liberal=c(0,0,0), 
                 conservative=c(0,0,0))

In the above set, I imagine "gov" and "dem" both at 1 point to the liberal column, while "biz" and "gop" add a point each to the conservative column. So, the ideal dataframe would be:

dfp <- data.frame(id=c("resp1", "resp2", "resp3"), 
                 cat1=c("gov", "biz", "biz"), 
                 cat2=c("dem", "gop", "dem"),
                 liberal=c(2,0,1), 
                 conservative=c(0,2,1))

I tried a for loop, but it didn't work.

for (i in length(dfp$liberal)){
  if (dfp[i,][,2] == "gov"){
    dfp[i,]$liberal = dfp[i,]$liberal + 1
  }
  if (dfp[i,][,3]=="gop"){
    dfp[i,]$conservative = dfp[i,]$conservative + 1
  }
}

If i get rid of the "i" iterator, the loop correctly adds the number liberal and conservative, but it adds it uniformly to all the rows.

thanks for any help and let me know if i can make this question any clearer. I'm a little new to loops, do if you also happen to have a function that would help me diagnose what i'm doing wrong, feel free to add to your explanation. thanks so much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You do not even need the "for" loop. Try

dfp <- data.frame(id=c("resp1", "resp2", "resp3"), 
              cat1=c("gov", "biz", "biz"), 
              cat2=c("dem", "gop", "dem"))

dfp$liberal = as.numeric(dfp$cat1=="gov") + as.numeric(dfp$cat2=="dem")

dfp$conservative = as.numeric(dfp$cat1=="biz") + as.numeric(dfp$cat2=="gop")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...