2016-03-23 33 views
0

我如何在中的每個值上應用以下函數rtxy具有以下值。如何在r中的數據幀上應用函數

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

'rt(x,y,unlist(df))'?你確定你確實需要'df'作爲'data.frame'而不是'matrix'嗎? – MichaelChirico

+0

是的,我想把它作爲數據幀 – HaagenDaz

+0

http://stackoverflow.com/questions/5158790/data-frame-or-matrix – MichaelChirico

回答

2

也許最簡單的,如果你想堅持用dataframes是使用applyMARGIN參數設置爲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)) 
+0

感謝這個作品 – HaagenDaz