对于具有多个R函数的if条件的循环 [英] For loop with if condition on multiple R functions

查看:1403
本文介绍了对于具有多个R函数的if条件的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,并不太了解R中函数背后的逻辑。我想创建一个能够处理四个变量的函数,其中三个条件决定第四个变量的结果;这遍及数据集中的所有情况。为简单起见,假设我的数据框有四个变量(var1到var4),每个变量有100个案例:

I'm new to programming and don't quite understand the logic behind functions in R just yet. I want to create a function which is able to handle four variables, with conditions in three of these deciding the result in the fourth variable; and that goes through all cases in the data set. For the sake of simplicity, lets say my data frame has four variables (var1 to var4) with 100 cases each:

f1 <- function(w, x, y, z) {
   for (n in seq_along(w)) {
    if (!is.na(w[n]) & !is.na(x[n]) & !is.na(y[n])){
  z[n]<-0
}else if (!is.na(w[n]) & !is.na(x[n]) & is.na(y[n])){
  z[n]<-1
}else if (!is.na(w[n]) & is.na(x[n]) & is.na(y[n])){
  z[n]<-2
}else if (!is.na(w[n]) & is.na(x[n]) & !is.na(y[n])){
  z[n]<-3
} } }

f1(df $ var1,df $ var2,df $ var3,df $ var4 )

为什么功能不起作用?

Why doesn't the function work?

推荐答案

您要在<$ c $内修改的变量 z c> f1 是本地副本,并且未在原始数据集 df 中更新。您需要返回修改后的 z 并将其分配给 df var4 $ C>。

The variable z that you are modifying inside f1 is a local copy and doesn't get updated in the original data-set df. You need to return the modified z and assign it to var4 in df.

f1 <- function(w, x, y, z) {
  for (n in seq_along(w)) {
    if (!is.na(w[n]) & !is.na(x[n]) & !is.na(y[n])){
      z[n]<-0
    } else if (!is.na(w[n]) & !is.na(x[n]) & is.na(y[n])) {
      z[n]<-1
    } else if (!is.na(w[n]) & is.na(x[n]) & is.na(y[n])) {
      z[n]<-2
    } else if (!is.na(w[n]) & is.na(x[n]) & !is.na(y[n])) {
      z[n]<-3
    } 
  } 
  z  # <--- return value 
}

然后拨打 f1

df$var4 <- f1(df$var1, df$var2, df$var3, df$var4)

这篇关于对于具有多个R函数的if条件的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆