使用 if 语句循环数据帧应用函数的行 [英] Loop over rows of dataframe applying function with if-statement
问题描述
我是 R 新手,如果要求和的两个元素都满足给定条件,我正在尝试对给定数据帧的 2 列求和.为了说清楚,我想做的是:
I'm new to R and I'm trying to sum 2 columns of a given dataframe, if both the elements to be summed satisfy a given condition. To make things clear, what I want to do is:
> t.d<-as.data.frame(matrix(1:9,ncol=3))
> t.d
V1 V2 V3
1 4 7
2 5 8
3 6 9
> t.d$V4<-rep(0,nrow(t.d))
> for (i in 1:nrow(t.d)){
+ if (t.d$V1[i]>1 && t.d$V3[i]<9){
+ t.d$V4[i]<-t.d$V1[i]+t.d$V3[i]}
+ }
> t.d
V1 V2 V3 V4
1 4 7 0
2 5 8 10
3 6 9 0
我需要一个高效的代码,因为我的真实数据框大约有 150000 行和 200 列.这给出了一个错误:
I need an efficient code, as my real dataframe has about 150000 rows and 200 columns. This gives an error:
t.d$V4<-t.d$V1[t.d$V1>1]+ t.d$V3[t.d$V3>9]
申请"是一种选择吗?我试过这个:
Is "apply" an option? I tried this:
t.d<-as.data.frame(matrix(1:9,ncol=3))
t.d$V4<-rep(0,nrow(t.d))
my.fun<-function(x,y){
if(x>1 && y<9){
x+y}
}
t.d$V4<-apply(X=t.d,MAR=1,FUN=my.fun,x=t.d$V1,y=t.d$V3)
但它也给出了错误.非常感谢您的帮助.
but it gives an error as well. Thanks very much for your help.
推荐答案
此操作不需要循环、apply 语句或 if 语句.您只需要矢量化操作和子集:
This operation doesn't require loops, apply statements or if statements. Vectorised operations and subsetting is all you need:
t.d <- within(t.d, V4 <- V1 + V3)
t.d[!(t.d$V1>1 & t.d$V3<9), "V4"] <- 0
t.d
V1 V2 V3 V4
1 1 4 7 0
2 2 5 8 10
3 3 6 9 0
<小时>
为什么这样做?
Why does this work?
在第一步中,我创建了一个新列,它是列 V1 和 V4 的直和.我使用 within
作为引用 d.f
列的便捷方式,而不必一直写 d.f$V
.
In the first step I create a new column that is the straight sum of columns V1 and V4. I use within
as a convenient way of referring to the columns of d.f
without having to write d.f$V
all the time.
在第二步中,我对所有不满足条件的行进行子集化,并将这些行的 V4 设置为 0.
In the second step I subset all of the rows that don't fulfill your conditions and set V4 for these to 0.
这篇关于使用 if 语句循环数据帧应用函数的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!