Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new column in data frame in R by comparing 2 existing columns and then deleting the latter

I have yet another question which I have been trying to solve for the past few hours unsuccessfully. It involves some dataset manipulation in R. Imagine that I have the following sample dataset:

a,b,v,r
1,3,1,0
2,5,1,1
3,6,0,1
1,5,1,0
2,4,1,1
3,6,0,1

I need to create a third column (say m) by comparing the values of the columns [v,r] by the following rules. If v = 1, r = 0 then m = 0. If v = 1, r = 1, then m = 1 and if v = 0, r = 1, then m = 2. [v,r] can never take the values (0,0).

I am wondering how I can create the third column and also delete the columns v,r in one line. Thank you !

like image 631
Shion Avatar asked Nov 30 '25 08:11

Shion


2 Answers

Using data.table (1.8.8):

DT <- data.table(DF)
DT[, `:=`(m = (!v) * 1 + r, v = NULL, r=NULL)]
#    a b m
# 1: 1 3 0
# 2: 2 5 1
# 3: 3 6 2
# 4: 1 5 0
# 5: 2 4 1
# 6: 3 6 2
like image 51
Arun Avatar answered Dec 02 '25 23:12

Arun


It's not one line (so not nearly as snappy as @Arun's data.table solution) but here is one approach with within and ifelse:

within(mydf, {
  m <- ifelse(v == 1 & r == 0, 0, ifelse(v == 1 & r == 1, 1, 2))
  rm(v, r)
})
#   a b m
# 1 1 3 0
# 2 2 5 1
# 3 3 6 2
# 4 1 5 0
# 5 2 4 1
# 6 3 6 2
like image 32
A5C1D2H2I1M1N2O1R2T1 Avatar answered Dec 02 '25 23:12

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!