对列中的每个单元格应用函数,并将结果添加到新列 [英] Apply function on each cell in a column and add the result to a new column

查看:109
本文介绍了对列中的每个单元格应用函数,并将结果添加到新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.table如下所示。我想要的是对C列中的每个元素应用一个函数。函数将接收一个向量(因为Col C包含向量元素)并返回另一个向量。这个结果向量应该被添加到一个新的列。

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)

例如,让我们考虑一个函数'isOdd',它接受一个向量并返回一个逻辑向量。应用此函数后的输出表应为

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)

如何实现这一点?

推荐答案

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

这篇关于对列中的每个单元格应用函数,并将结果添加到新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆