简体   繁体   English

应用函数ifelse总结两列

[英]apply function ifelse summing up two columns

I would like to find a solution for the following problem, hope someone can help me. 我想找到以下问题的解决方案,希望有人可以帮助我。 I have a dataframe with over 2000 columns and I need just two of them. 我有一个超过2000列的数据框,我只需要其中两个。 First I need to check if the sums (df$values1 + df$values2.) of the two columns are than 15. Now I would like to have a result column: If yes: 15 If no: sum up the values of the first to the second column, so that df$values1 + df$values2. 首先,我需要检查两列的总和(df $ values1 + df $ values2。)是否大于15。现在我想要一个结果列:如果是:15如果否:将第一列的值求和到第二列,以便df $ values1 + df $ values2。

I tried to get an result with the following, but it doesn't work: 我试图获得以下结果,但不起作用:

df$result <- apply(df[which(colnames(df)=="values1")],2, 
    function(x) {ifelse(df[which(colnames(df)=="values2")]+x >= 15, 15, df[which(colnames(df) == "values2")] + x)
    }
)

Thanks! 谢谢!

如果我正确理解:

df$sumOfValues = pmin(df$values1 + df$values2, 15)

Welcome to StackOverflow. 欢迎使用StackOverflow。

From now on, make sure that you post reproducible questions if you would like to get any help from here. 从现在开始,如果您想从这里获得任何帮助,请确保您发布可重复的问题。

First of all, let's look at your code. 首先,让我们看一下您的代码。

df$result <-
  apply(df[which(colnames(df) == "values1")], 2, function(x) {
    ifelse(df[which(colnames(df) == "values2")] + x >= 15,
           15,
           df[which(colnames(df) ==
                      "values2")] + x)
  })

Your code "says": for each column called values1 in df if any value in values2 in df + the value in values1 is equal or greater than 15 , assign the value 15 , else assign values2 + the values in values1 . 您的代码“说”:名为值1的DF如果任何值每列values2df +中值values1等于或大于15 ,分配值15 ,否则分配values2 +中的值values1

Basically, you are replacing a single number with a vector, hence you are returning a list. 基本上,您是用向量替换单个数字,因此要返回一个列表。

Tips: 提示:

1) Don't refer to your columns by using which . 1)不要使用which来引用您的列。 Instead, directly subset your data, either by using df[,1] or similar or by df$values1 . 而是使用df[,1]或类似方法或df$values1直接子集数据。

2) Don't use apply when applying a function on 1-dimensional data. 2)将功能应用于一维数据时,请勿使用apply

Solutions, either the example written by kgolyaev above or, if you would like to use ifelse you could go by: 解决方案,或者上面的kgolyaev编写的示例 ,或者,如果您想使用ifelse ,则可以通过以下方法:

ifelse(df$values1 + df$values2 >= 15,
       15, df$values1 + df$values2)

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

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