Reputation: 11
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!
Upvotes: 1
Views: 305
Reputation: 1373
Welcome to StackOverflow.
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
indf
+
the value invalues1
is equal or greater than15
, assign the value15
, else assignvalues2
+ the values invalues1
.
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)
Upvotes: 0
Reputation: 565
If I understand it correctly:
df$sumOfValues = pmin(df$values1 + df$values2, 15)
Upvotes: 2