简体   繁体   中英

assign values to vector in a dataframe based on conditions from other vectors in R

so I have a partially empty dataframe and I need to assign values to a vector that we may call "C" based on different outcomes of an other vector which we may call B. The values to assign to C are taken, in some determined cases, from a third vector, "A". How can I do that? I tried if statements and for loops but don't know how to do them properly. Here's summarized my problem. Thank you for your answers

A = (1,2,3,4,5,6,7,8,9,10)

B = (1,0,1,2,1,0,0,2,0,1)

C = 0            if B = 0  
  =A(same row)   if B = 1
  =-A(same row)  if B =-1     

An option is to get the sign of 'B' and multiply with 'A'

C <- sign(B) * A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM