[英]how to apply functions on data frame in r
How can i apply the following function rt
on each and every value l
in df
. 我如何将以下函数rt
应用于df
每个值l
。 x
and y
have the following values. 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
Probably simplest if you'd like to stick with dataframes is to use apply
with the MARGIN
parameter set to c(1,2)
, which makes it apply the function by both rows and columns (ie, to every cell). 如果您想坚持使用数据框,最简单的方法就是使用apply
MARGIN
参数设置为c(1,2)
apply,这使它可以按行和按列(即,对每个单元格)应用该函数。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.