简体   繁体   中英

R how to add another column to a dataset based on 2 other columns

I have a data set of messages exchanged in an organization, I want to create another column based on case_when the sender_department == receiver_department , assign "intra" while if the sender_department != receiver_department , assign "inter" .

I'm doing this to know the proportion of inter and intra departmental messages over the period.

I've use the code below

intra_inter_msg <- DF %>%
  mutate(inter_intra = case_when(sender_department == receiver_department, ~"intra",         ,
                                 sender_department != receiver_department, ~"inter"))

and I got this error

Error in mutate() :
! Problem while computing inter_intra = case_when(...) . Caused by error in case_when() :
! Case 1 ( sender_department == receiver_department ) must be a two-sided formula, not a logical

I made a little example DF to test it:

require(dplyr)
DF = data.frame (sender_department = c("econ","math","history"),receiver_department = c("econ","history","math"))
DF
intra_inter_msg <- DF %>%
  mutate(inter_intra = case_when(sender_department == receiver_department ~"intra",         
                                 sender_department != receiver_department ~"inter"))
intra_inter_msg

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