简体   繁体   English

通过R中的嵌套函数更新数据框

[英]Update Data Frame through nested functions in R

I have a small reproducible version of the issue I'm having with my program. 我在程序中遇到的问题有一个可重现的小版本。

The structure of my code involves nested functions, similar to the one shown below, only more complex. 我的代码结构涉及嵌套函数,类似于下面显示的函数,只是嵌套函数更复杂。

x <- data.frame(c(1:5),c(0))
colnames(x) <- c("val1", "val2")

foo <- function() {
  for(i in 1:length(x[,1])) {
    bar(i)
  }
  print(x)
}

bar <- function(i) {
   if(x[i,2] == 0) {
    x[i,2] <- 1
    print(x[i,])
  }
  return(x)
}

>foo()
  val1 val2
1    1    1
  val1 val2
2    2    1
  val1 val2
3    3    1
  val1 val2
4    4    1
  val1 val2
5    5    1
  val1 val2
1    1    0
2    2    0
3    3    0
4    4    0
5    5    0

So as the results show, the value is not being returned from the bar() function in order to update the data frame. 因此,如结果所示,为了更新数据框,没有从bar()函数返回该值。

What do I need to change in order to return an updated table to the foo() function? 为了将更新后的表返回给foo()函数,我需要更改什么?

Thanks in advance. 提前致谢。

It's better to pass the data.frame as an argument instead of hard coding it to the function. 最好将data.frame作为参数传递,而不是将其硬编码到函数中。 Here are some modifications that should accomplish what you're looking for 这是一些可以满足您需求的修改

foo <- function(df) {
  for(i in seq_len(nrow(df))) {
    df[i, ] <- bar(df[i, ])
  }
  print(df)
}

bar <- function(df) {
  if(df[, "val2"] == 0) {
    df[, "val2"] <- 1
    print(df[, ])
  }
  return(df)
}

> foo(x)
  val1 val2
1    1    1
  val1 val2
2    2    1
  val1 val2
3    3    1
  val1 val2
4    4    1
  val1 val2
5    5    1
  val1 val2
1    1    1
2    2    1
3    3    1
4    4    1
5    5    1

So I'm a bit confused as to why you need to write a function to accomplish this. 因此,我对为什么需要编写一个函数来完成此操作感到困惑。 By far the simplest solution would just be to subset the dataframe conditionally and assign the value: 到目前为止,最简单的解决方案只是有条件地对数据帧进行子集并分配值:

  x <- data.frame(c(1:5),c(0))
  colnames(x) <- c("val1", "val2")


  x$val2[x$val2==0]<-1

However, if this is too simplistic an answer, as in the solution needs to scale, I suspect that embedding one of the apply functions would likely work. 但是,如果答案太简单了(如需要扩展解决方案中的解决方案),我怀疑嵌入应用功能之一可能会起作用。

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

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