有条件地创建一个新列 [英] Conditionally creating a new column

查看:159
本文介绍了有条件地创建一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相当确定这是一个非常明显的问题,但我无法想像。

I am fairly certain this is a really obvious question, but I can't figure it out.

让我说我有以下数据集:

Lets say I have the following dataset:

test <- data.frame(A = c(1:10),
              B = c(1:10), C = c(1:10),
              P = c(1:10))

我想测试一下,如果有一个名为P的列,创建一个名为Z的列,并从P中计算出一些内容。

And I want to test, if there is a column called "P", create a new column called "Z" and put some content in it calculated from P.

我写了以下代码(只是为了尝试获得它有条件地创建列,我没有试图让它做任何事情,但是!):

I wrote the following code (just to try and get it to conditionally create the column, I've not tried to get it to do anything with that yet!):

Clean <- function(data) {
  if("P" %in% colnames(data)) {        
    data$Z <- NA
      }
  else {
    cat("doobedooo")
      }
    }
Clean(test)

但它似乎没有任何作用,我不明白为什么只要运行 test $ Z < - NA 在数据集doe上的工作
我把doobedooo放在那里,看看它是否在第一个条件下返回false。好像没有这样做。

But it doesn't seem to do anything, and I don't understand why, when simply running test$Z <- NA on the dataset does work. I put the "doobedooo" in there, to see if it is returning a false at the first condition. It doesn't seem to be doing so.

我只是误解语句如何工作?

Have I simply misunderstood how if statements work?

推荐答案

您必须从函数返回值,然后将该值分配给对象。与许多其他语言不同,R不会在现场修改对象,至少没有大量的工作。

You have to return a value from your function, and then assign that value to an object. Unlike many other languages, R doesn't modify objects in-place, at least not without a lot of work.

Clean <- function(data) {
    if("P" %in% colnames(data)) {        
        data$Z <- NA
    } else {
        cat("doobedooo"
    }
    return(data)
}
test <- Clean(test)

这篇关于有条件地创建一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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