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
377 views
in Technique[技术] by (71.8m points)

r - add column values based on other columns in data frame using for and if

I have a dataframe like this:

     id        adit     diag1   diag2       
      2       3         4230    2234        
      3       5         3345    4456        
      4       6         4567    4467

I would like to add other 2 columns, dse1 and dse2 using the pseudo-code below:

if diag1 contains 4230 then dse1 = 1 else dse1 = 0

if diag2 contains 4567 then dse2 =1  else dse2 = 0

I used this:

for (i in 1 : nrow(dse)){
  for (j in 3: ncol(dse)){
     if dse[i,j] %in% ("4320"){dse$dse1 = 1}
        else{dse$dse1 = 0}
    if dse[i,j] %in% ("4567"){dse$dse2 = 1}
        else{dse$dse2 = 0} 
  }
}

But these do not work.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

No need to use a loop, just use ifelse, for example

dse = within(dse, {
    dse1 = ifelse(diag1 == 4230, 1, 0)
    dse2 = ifelse(diag2 == 4567, 1, 0)
 })

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

...