简体   繁体   中英

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. 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.

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.

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 .

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 . Instead, directly subset your data, either by using df[,1] or similar or by df$values1 .

2) Don't use apply when applying a function on 1-dimensional data.

Solutions, either the example written by kgolyaev above or, if you would like to use ifelse you could go by:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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