我写了一个for循环来操作一个相当大的(~1,000,000行)数据帧,但它运行得太慢而且我在网上找不到任何东西。
df=data.frame(v1=runif(10), v2=runif(10), v3=runif(10), v4=0, v5=0, v6=0, v7=0)
for( i in 1:dim(df)[1] ) {
df[i,4]=length(which(df[i,1:3]>0.00 & df[i,1:3]<0.10))
df[i,5]=length(which(df[i,1:3]>0.10 & df[i,1:3]<0.50))
df[i,6]=length(which(df[i,1:3]>0.50 & df[i,1:3]<0.90))
df[i,7]=length(which(df[i,1:3]>0.90 & df[i,1:3]<1.00))
}
我尝试编写一个函数来执行此操作,但它将所有行添加到一起:
test.fun <- function (df) {
df[,4]=length(which(df[,1:3]>0.00 & df[,1:3]<0.10))
df[,5]=length(which(df[,1:3]>0.10 & df[,1:3]<0.50))
df[,6]=length(which(df[,1:3]>0.50 & df[,1:3]<0.90))
df[,7]=length(which(df[,1:3]>0.90 & df[,1:3]<1.00))
return(df)
}
(test <- test.fun(df))
答案 0 :(得分:4)
rowSums
是主要想法。
您可以使用 dplyr
软件包 来使其更清晰:
df %>%
mutate(v4 = rowSums(df[,1:3]>0.00 & df[,1:3]<0.10))%>%
mutate(v5 = rowSums(df[,1:3]>0.10 & df[,1:3]<0.50))%>%
mutate(v6 = rowSums(df[,1:3]>0.50 & df[,1:3]<0.90))%>%
mutate(v7 = rowSums(df[,1:3]>0.90 & df[,1:3]<1.00))
# v1 v2 v3 v4 v5 v6 v7
# 1 0.2875775 0.95683335 0.8895393 0 1 1 1
# 2 0.7883051 0.45333416 0.6928034 0 1 2 0
# 3 0.4089769 0.67757064 0.6405068 0 1 2 0
# 4 0.8830174 0.57263340 0.9942698 0 0 2 1
# 5 0.9404673 0.10292468 0.6557058 0 1 1 1
# 6 0.0455565 0.89982497 0.7085305 1 0 2 0
# 7 0.5281055 0.24608773 0.5440660 0 1 2 0
# 8 0.8924190 0.04205953 0.5941420 1 0 2 0
# 9 0.5514350 0.32792072 0.2891597 0 2 1 0
# 10 0.4566147 0.95450365 0.1471136 0 2 0 1
<强> 数据:的强>
set.seed(123) #to make a reproducible example
df=data.frame(v1=runif(10), v2=runif(10), v3=runif(10), v4=0, v5=0, v6=0, v7=0)