如何将函数应用于 R 数据框中的列并将输出存储在一个数据框中

How to apply a function to a column in R data frame and store output in one dataframe

我有这样一个数据框

set.seed(12)
df=data.frame(a=runif(20,-100,100),b=rep(c("a","b"),10))

现在我需要计算出 'a' 列中有多少百分比的值的绝对值 < n,并且 n 是一个变量:10、20、30、40、50,并将结果输出到像这样的数据框

n              10 20 30 40 50
% in the range 12% 14% 27% 40% 50%

列表结果:

n <- seq(10,50, by = 10)
list <- lapply(n, function(x) percent(sum(abs(df$a) < x)/nrow(df)))
setNames(list, n)

对于数据框:

df <- do.call(rbind, list)

这是return数据框

的方法
# get a named vector of values
myValues <- setNames(seq(10, 50, 10), seq(10, 50, 10))
# return result
data.frame(lapply(myValues, function(x) sum(abs(df$a) < x) / nrow(df)))
X10  X20  X30 X40 X50
1 0.1 0.15 0.35 0.4 0.5

更简单的是 return 具有相同信息的命名向量。

myPropVec <-sapply(myValues, function(x) sum(abs(df$a) < x) / nrow(df))
myPropVec
  10   20   30   40   50 
0.10 0.15 0.35 0.40 0.50

将命名向量绘制为条形图很简单:

barplot(myPropVec)

或使用dotchart:

dotchart(myPropVec)

这样的东西可以为您提供矢量输出

n<-seq(10,50,10)

perc<-vector()

for(i in 1:5) {perc[i]<-sum(abs(df$a)<n[i])/length(df$a)}

perc
[1] 0.10 0.15 0.35 0.40 0.50