r - Swapping values between two columns using data.table -
i have been breaking head on translating this question data.table
solution. (to keep simple i'll use same data set)
when v2 == "b
want swap columns between v1 <-> v3
.
dt <- data.table(v1=c(1,2,4), v2=c("a","a","b"), v3=c(2,3,1)) #v1 v2 v3 #1: 1 2 #2: 2 3 #3: 4 b 1
the code below working solution data.frame
, because of amount of frustration has given me because using data.table
without realising i'm determined find solution data.table.
dt <- data.table(v1=c(1,2,4), v2=c("a","a","b"), v3=c(2,3,1)) df <- as.data.frame(dt) df[df$v2 == "b", c("v1", "v3")] <- df[df$v2 == "b", c("v3", "v1")] # v1 v2 v3 #1 1 2 #2 2 3 #3 1 b 4
i have tried writing lapply
function looping through target swapping list, tried narrow down problem replace 1 value, attempted call column names in different ways without success.
closest attempt i've managed get:
> dt[dt$v2 == "b", c("v1", "v3")] <- dt[dt$v2 == "b", c(v3, v1)] #warning messages: #1: in `[<-.data.table`(`*tmp*`, dt$v2 == "b", c("v1", "v3"), value = c(1, : # supplied 2 items assigned 1 items of column 'v1' (1 unused) #2: in `[<-.data.table`(`*tmp*`, dt$v2 == "b", c("v1", "v3"), value = c(1, : # supplied 2 items assigned 1 items of column 'v3' (1 unused)
how can data.table solution?
we can try
dt[v2=="b", c("v3", "v1") := .(v1, v3)]
Comments
Post a Comment