【发布时间】:2013-12-28 18:03:05
【问题描述】:
我有一个数据集,需要根据另一个数据集的值进行封顶/修剪等。两个数据集具有相同的结构(列名等)。
将存储在另一个数据集中的转换应用于当前数据集的快速方法是什么?
样本数据:
#generate sample data & set some values to NA
#this is the dataset that has variables that need to be trimmed
x1 <- data.frame(a=rep(11:20), b=rep(41:50))
x1[2,1] <- NA
x1
#a vector containing values to trim to (in this case, say 75th percentile)
y1 <- apply(x1, 2, function(x) quantile(x, 0.75, na.rm=T))
y1
#I am doing this inside a loop
for (i in 1:ncol(x1)){
x1[is.na(x1[[i]]),] <- y1[i] #if missing, set to some value
x1[x1[[i]] > y1[i], i] <- y1[i] #if larger than 75th pctl, set to some value
}
x1
我很确定有一种更快的矢量化方法可以做到这一点。非常感谢任何意见。
【问题讨论】:
标签: r for-loop vectorization apply