r - Recode 2 variables to one in one line -


say have df like:

df=data.frame(a=c(0,0,1,1),b=c(0,1,0,1)) 

only has long no. of rows. i'd create column depending on simultaneous values of & b, e.g

df  b  c 0  0  10 0  1  11 1  0  12 1  1  13 

i take can done inner joins, using sqldf or maybe dplyr; there quicker way, or without libraries?

thanks in advance, p

i think mean have other data frame (say called dictionary) c column, , (a, b) in dictionary , grab c there??

df=data.frame(a=c(0,0,1,1),b=c(0,1,0,1)) dictionary <- df dictionary$c <- 10:13 dictionary <- dictionary[sample(4), ] # shuffle prove works 

in case can do

merge(df, dictionary, merge=c('a', 'b'), all.x=t) 

and grab matching c column dictionary , plonk df. all.x put na there if there no matching (a, b) in dictionary.

if speed becomes issue, might try data.table

library(data.table) setdt(df)         # convert data.table setdt(dictionary) # convert data.table # set key setkey(df,a,b) setkey(dictionary,a,b) # merge dictionary[df] # `df` `c` column added, `na` if no match 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -