r - Subsetting and assignment on several columns of a data table -
lets have info table 1 below:
library(data.table) n = 10 x = data.table(id = 1:n, segm = sample(c("a","b","c"),n,replace=t), r = rnorm(n,20,5), aa = sample(0:1,n,replace=t), ab = sample(0:1,n,replace=t), ba = sample(0:1,n,replace=t), bb = sample(0:1,n,replace=t))
i'd know how substitute 1 values na
columns aa
, ab
, ba
, bb
using info table package. know how using info frame.
i tried using following:
f = c("aa","ab","ba","bb") x[,f,with=f][x[,f,with=f]==1] <- "na"
but i'm getting error: error in [<-.data.table(*tmp*, , f, = f, value = list(aa = c("0", : unused argument (with = f)
to sum up, question is: how can subset , assign on several columns of info table @ same time.
the line of code:
x[f==1,f:="na"]
is not working. why?
any help appreciate.
there's nil wrong using for()
loop here.
given nature of problem, different subset of rows beingness operated on in each of 4 columns, you're going need utilize some sort of loop; might build explicit 1 allows take total advantage of data.table's modify-by-reference :=
operator.
for (i in f) x[get(i)==1, (i):=na] x # id segm r aa ab ba bb # 1: 1 c 15.203246 na na 0 0 # 2: 2 b 23.536583 na 0 0 na # 3: 3 16.404203 na 0 na 0 # 4: 4 18.673618 0 0 na na # 5: 5 c 30.528967 na 0 na na # 6: 6 18.887781 0 na na na # 7: 7 c 24.476124 0 0 na na # 8: 8 b 26.862686 0 0 na 0 # 9: 9 c 9.047837 0 0 0 na # 10: 10 c 17.532379 0 0 na na
r data.table
No comments:
Post a Comment