dataframe - R how to retrieve data from data.frame with multiple conditions -
i wondering how perform basic data manipulation in r. want following.
i have data table following pattern :
v1 v2 v3 abc x 24 abc y 30 efg x 4 efg y 28 hij p 40 hij y 41 pkl x 32
now want retrieve values/pairs of v1 doesn't have corresponding value not x on v2. in above dataset subset
hij p 40 hij y 41
since neither of pair of hij have v2 value of x.
i retrieve values of v1 don't repeat twice. in above example
pkl x 32
you mentioned data.table
, here's 2 possible approaches both requests
library(data.table)
for 1.
setdt(df)[, .sd[all(v2 != "x")], = v1] # v1 v2 v3 # 1: hij p 40 # 2: hij y 41
for 2.
df[, .sd[.n == 1l], = v1] # v1 v2 v3 # 1: pkl x 32
or (a bit more optimized version)
indx <- df[, .(indx = .i[.n == 1l]), = v1]$indx df[indx] # v1 v2 v3 # 1: pkl x 32
Comments
Post a Comment