如何在r中的数据帧上应用函数

时间:2016-03-23 14:02:39

标签: r

如何对rt中的每个值l应用以下函数df。  xy具有以下值。

 x<-9
 y<-1

rt<-function(x,y,l) min(x,max(0,l-y))

df
a   b   c
5   6   7
1   4   1
2   4   3

1 个答案:

答案 0 :(得分:2)

如果你想坚持使用数据帧,可能最简单的方法是使用apply MARGIN参数设置为c(1,2),这样就可以通过行和列应用函数(即,每个细胞。)

x <- 9
y <- 1

rt <- function(x, y, l) min(x, max(0, l-y))

df <- data.frame(a = c(5, 1, 2),
                 b = c(6, 4, 4),
                 c = c(7, 1, 3))

rt_df <- as.data.frame(apply(df, c(1,2), rt, x = x, y = y))