简体   繁体   English

R:在 ifelse 语句中将特定行馈送到 function

[英]R: Feed specific row to function in ifelse statement

I am using an ifelse statement to create a new column in my dataframe.我正在使用 ifelse 语句在我的 dataframe 中创建一个新列。

Inside this ifelse statement I need to call a function on results which pass the initial test.在这个 ifelse 语句中,我需要对通过初始测试的结果调用 function。

For example:例如:


test_function=function(value){
   print(value)
   return(value)}

testdf<-data.frame(a=c(1,1,2,2,3,3),b=c(1,2,3,4,5,6))

testdf$c<-ifelse(testdf$a==2,test_function(testdf$b),NA)

This example does give the answer I would expect (testdf$c= NA,NA,3,4,NA,NA), however the print statement shows that along the way all of column a is being passed to test_function().这个例子确实给出了我所期望的答案(testdf$c= NA,NA,3,4,NA,NA),但是打印语句显示所有列 a 都被传递给 test_function()。

In my actual data this causes a fail (apologies, I'm really struggling to provide a reproducible example).在我的实际数据中,这会导致失败(抱歉,我真的很难提供一个可重现的例子)。

Is there any way to alter this so that only those rows that pass the initial test are passed to the function rather than all rows with the decision seemingly made after.有什么办法可以改变这一点,以便只有通过初始测试的那些行被传递给 function,而不是似乎在之后做出决定的所有行。

I'm aware I could achieve the same with an apply function, or a loop but my actual dataframe is 1.5m rows long and I have found these to be prohibitively time consuming.我知道我可以通过应用 function 或循环来实现相同的效果,但我的实际 dataframe 是 1.5m 行长,我发现这些非常耗时。

Thanks in advance for your help!在此先感谢您的帮助!

If you want the results of a function in ifelse , save the output and pass it to the function.如果您想要 ifelse 中ifelse的结果,请保存 output 并将其传递给 function。 Otherwise use and if{}else{} construct inside the function.否则,在 function 中使用if{}else{}构造。

x <- test_function(testdf$b)
[1] 1 2 3 4 5 6
testdf$c <- ifelse(testdf$a==2, x, NA)
testdf$c
[1] NA NA  3  4 NA NA

You could get the index where a = 2 and pass it to test_function .您可以获得a = 2的索引并将其传递给test_function

inds <- testdf$a == 2
testdf$c <- NA
testdf$c[inds] <- test_function(testdf$b[inds])

This prints in the console:这将在控制台中打印:

#[1] 3 4

and testdf is:testdf是:

testdf
#  a b  c
#1 1 1 NA
#2 1 2 NA
#3 2 3  3
#4 2 4  4
#5 3 5 NA
#6 3 6 NA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM