r - Apply function on each cell in a column and add the result to a new column -


i have data.table shown below. want apply function each of elements in column c. function take in vector(since col c contains vector elements) , return vector. resultant vector should added new column.

       b         c         1:  16  151 c(2579, 2659, 2752) 2:  16  152 c(2580, 2660, 2753)  3:  16  153 c(2581, 2661, 2754) 4:  16  154 c(2582, 2662, 2755) 5:  16  155 c(2583, 2663, 2756) 6:  16  156 c(2584, 2664, 2757) 

for example let consider function 'isodd' takes in vector , returns logical vector. output table after applying function should like

       b           c            isodd 1:  16  151 c(2579, 2659, 2752)  c(t,t,f) 2:  16  152 c(2580, 2660, 2753)  c(f,f,t)  3:  16  153 c(2581, 2661, 2754)  c(t,t,f) 4:  16  154 c(2582, 2662, 2755)  c(f,f,t) 5:  16  155 c(2583, 2663, 2756)  c(t,t,f) 6:  16  156 c(2584, 2664, 2757)  c(f,f,t) 

how achieve this?

using r's apply functions, can accomplish goal. lets d data.table working with. lapply passes each row of column "c" anonymous function, further passes each element of passed in row function, isodd.

isodd <- function(x) {     if (x %% 2 == 0) return("f")      else return("t") }  d$isodd <- lapply(d$c, function(x) sapply(x, isodd)) 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -