r - Preventing apply from returning a vector? -
i'm running large number of data frames variable dimensions through series of apply() calls code below.
df1 = t(data.frame('test'=c(0,0,1,0))) df1 = apply(df1,2,function(j){sub(0,'00',j)}) df1 = apply(df1,2,function(j){sub(1,'01',j)}) df1 = apply(df1,2,function(j){sub(2,'10',j)}) df1
in rare cases data frame size 1xn first apply() call cause return vector data type , causing error subsequent applys. note problem not appear occur 1xn data frames (in above code, remove t()). there quick/clean way prevent apply() returning vectors or other efficient workarounds issue?
i think following might work when 1xn no nx1 data-frames used input.
df1 = apply(df1,1,function(j){sub(0,'00',j)}) df1 = apply(df1,2,function(j){sub(1,'01',j)}) df1 = apply(df1,2,function(j){sub(2,'10',j)}) t(ret)
the following preserves original data structure. what's looked for?
df = data.frame('test'=c(0,0,1,0)) df[] <- apply(df,2,function(j){sub(0,'00',j)}) df[] <- apply(df,2,function(j){sub(1,'01',j)}) df[] <- apply(df,2,function(j){sub(2,'10',j)}) df # test # 1 00 # 2 00 # 3 01 # 4 00 df1 = t(data.frame('test'=c(0,0,1,0))) df1[] <- apply(df1,2,function(j){sub(0,'00',j)}) df1[] <- apply(df1,2,function(j){sub(1,'01',j)}) df1[] <- apply(df1,2,function(j){sub(2,'10',j)}) df1 # [,1] [,2] [,3] [,4] # test "00" "00" "01" "00"
Comments
Post a Comment