【问题标题】:Trying to write a function in r that computes a variable and assigns levels and labels尝试在 r 中编写一个计算变量并分配级别和标签的函数
【发布时间】:2019-09-06 14:59:18
【问题描述】:

我正在尝试编写一个函数(这方面非常新),它使用 ifelse 来计算一个新变量,然后给这个新变量一个标签并给出级别标签。然后通过运行频率和交叉表检查它是否有效。如果我在硬编码的步骤中执行它,我可以让它工作,但我正在努力让它作为一个函数工作。

这就是我希望该函数执行的操作并且它有效:

  df$new_variable<-ifelse(df$other_variable==0,1,0)
  label(df$new_variable) <- "Not applicable"
  levels(df$Snew_variable) <- list(No=0, Yes=1)
  frq(df, new_variable) #see that it created the new variable     
  cro(df$other_variable, df$new variable) #see that it was created 
  correctly

这就是我一直在努力的工作:

    compute_new_var<-function(df, x) {
    df$new_variable<-ifelse(x==0,1,0)
    label (df$new_variable) <- "Not applicable" 
    levels(df$new_variable) <-list(No=0, Yes=1)
    frq(df, new_variable)
    cro(df$new_variable, x)
  }

compute_new_var(df_name, other_variable_name)

它正在做几件事。它不喜欢“标签”,所以我一直把标签和水平线放在外面。然后它给了我这个找不到对象“new_variable”的错误。我不确定我是否在参数中遗漏了一些东西,或者它是否没有创建 new_variable 或者它是否正在创建它但没有将它存储在我的 df 中,或者我是否只是想在这里塞进太多东西。有什么想法吗?

我希望它创建新变量,为变量分配标签,为值分配标签,并打印频率和交叉表。

【问题讨论】:

    标签: r function if-statement


    【解决方案1】:

    我不得不猜测一些软件包,因为其中一些功能有多个版本。请检查:)

    我认为唯一的问题是您在 x - other_variable_name 中向函数输入了列名字符,但您没有在数据中引用它。所以我在函数中用df[[x]]替换了x。这是唯一的主要区别。

    # please include all packages in the code. Are these right?
    library(Hmisc)
    library(sjmisc)
    library(expss)
    set.seed(1)
    # table with column called y
    df <- data.frame(y=sample(0:3, 10, replace=TRUE))
    
    compute_new_var <- function(df, x){
      # it was missing the reference to df
      df$new_variable <- ifelse(df[[x]]==0, 1, 0)
    
      # don't need to add package here, just doing it to highlight where they are used
      Hmisc::label(df$new_variable) <- "Not applicable" 
      levels(df$new_variable) <- list(No=0, Yes=1)
      sjmisc::frq(df, new_variable)
      return(expss::cro(df$new_variable, x))
    }
    
    compute_new_var(df, x="y")
    

    【讨论】:

    • 感谢您的帮助!!您猜的包是正确的,抱歉没有指定。所以我的下一个问题是,新变量去了哪里或者我该如何保存它?当我查找它或尝试从我的数据框中调用它时,我得到 NULL 或找不到对象。
    • R 函数只返回一个对象,因为它们旨在完成一项工作。您可以将其转换为两个功能,一个用于更新 df,另一个用于执行 cro 部分。另一种方法是使用list(df, cro(df..))。另外,我没有注意到cro 部分中的x。那可能需要df[[x]]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多