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 !
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With