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

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

ABC 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, consider the function 'isOdd', which takes a vector and returns a logical vector. After applying this function, the output table should look like

  ABC 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?

+4
source share
2 answers

Using the functions of R apply, we can easily achieve your goal. Suppose d is your data.table that you are working with. Basically lapply passes each row of the "C" column to an anonymous function, which then passes all the elements of the passed row to the isOdd function.

 isOdd <- function(x) { if (x %% 2 == 0) return("F") else return("T") } d$isOdd <- lapply(d$C, function(x) sapply(x, isOdd)) 
+1
source
 DT = data.table(A=letters[1:3], B=list(1:3,4:6,7:8)) DT AB # notice B is list column containing vectors of different lengths 1: a 1,2,3 # it isn't a character vector, although it prints like one 2: b 4,5,6 3: c 7,8 > DT[,L:=sapply(B,length)][] ABL 1: a 1,2,3 3 2: b 4,5,6 3 3: c 7,8 2 > isOdd = function (x) x%%2 == 0 > DT[,odd:=lapply(B,isOdd)][] ABL odd 1: a 1,2,3 3 FALSE,TRUE,FALSE 2: b 4,5,6 3 TRUE,FALSE,TRUE 3: c 7,8 2 FALSE,TRUE 
+2
source

Source: https://habr.com/ru/post/1478937/


All Articles