且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对列中的每个单元格应用函数,并将结果添加到新列

更新时间:2021-08-09 23:27:31

使用R的apply函数,目标。让我们说d是你正在使用的data.table。基本上lapply将列C的每一行传递给匿名函数,然后进一步将传入行中的每个元素传递给函数isOdd。

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))