如何对rt
中的每个值l
应用以下函数df
。
x
和y
具有以下值。
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
答案 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))