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

I have a data.table as shown below. What I want is to apply a function to each of the elements in column C. The function will take in a vector(since Col C contains vector elements) and return another vector. This resultant vector should be added to a new column.

     A   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 us consider a function 'isOdd' that takes in a vector and returns a logical vector. The output table after applying this function should look like

     A   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 do I achieve this?

Answers


Using R's apply functions, we can easily accomplish your goal. Lets say that d is your data.table you are working with. Basically lapply passes each row of column "C" to the anonymous function, which then further passes each element of the passed in row to the function, isOdd.

isOdd <- function(x) {
    if (x %% 2 == 0) return("F") 
    else return("T")
}

d$isOdd <- lapply(d$C, function(x) sapply(x, isOdd))

Need Your Help

How to best vertically center an image and some text inside a div

html css xhtml

I come up against this challenge frequently -- and when trying to solve I always wonder if I'm doing it wrong.

Color and Texture-Based Shadow Detection

matlab image-processing computer-vision video-processing matlab-cvst

I'm doing a project on tracking and Object classification in video surveillance,and i have some difficulties with removing the shadows from the foreground objects.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.