R how to change the value of a variable based on a condition using dplyr::mutate and if_else?
I'm trying to change a value of a variable in a data.frame where if a condition is met, then the variable takes another value, and if the condition is not met, the variable takes its original value. I'm confused why I'm getting an error and would like to know how can I modify my code to overcome this error.
For example, say I have the following dataset x
and I want to create a new variable var3
, such that if a condition is met, var3
takes 1, if not var3
takes its old value.
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(grep('a', var1)==1, 1, var3))
If I run this code I get the following error
Error in mutate_impl(.data, dots) :
Column `var3` must be length 3 (the number of rows) or one, not 2
The correct answer is
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
My real code is more complicated and I need to var3
to take its old value when the condition evaluates FALSE
, rather than just a singular value (say 0
).
What am I doing wrong here?
r if-statement dplyr mutate
add a comment |
I'm trying to change a value of a variable in a data.frame where if a condition is met, then the variable takes another value, and if the condition is not met, the variable takes its original value. I'm confused why I'm getting an error and would like to know how can I modify my code to overcome this error.
For example, say I have the following dataset x
and I want to create a new variable var3
, such that if a condition is met, var3
takes 1, if not var3
takes its old value.
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(grep('a', var1)==1, 1, var3))
If I run this code I get the following error
Error in mutate_impl(.data, dots) :
Column `var3` must be length 3 (the number of rows) or one, not 2
The correct answer is
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
My real code is more complicated and I need to var3
to take its old value when the condition evaluates FALSE
, rather than just a singular value (say 0
).
What am I doing wrong here?
r if-statement dplyr mutate
add a comment |
I'm trying to change a value of a variable in a data.frame where if a condition is met, then the variable takes another value, and if the condition is not met, the variable takes its original value. I'm confused why I'm getting an error and would like to know how can I modify my code to overcome this error.
For example, say I have the following dataset x
and I want to create a new variable var3
, such that if a condition is met, var3
takes 1, if not var3
takes its old value.
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(grep('a', var1)==1, 1, var3))
If I run this code I get the following error
Error in mutate_impl(.data, dots) :
Column `var3` must be length 3 (the number of rows) or one, not 2
The correct answer is
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
My real code is more complicated and I need to var3
to take its old value when the condition evaluates FALSE
, rather than just a singular value (say 0
).
What am I doing wrong here?
r if-statement dplyr mutate
I'm trying to change a value of a variable in a data.frame where if a condition is met, then the variable takes another value, and if the condition is not met, the variable takes its original value. I'm confused why I'm getting an error and would like to know how can I modify my code to overcome this error.
For example, say I have the following dataset x
and I want to create a new variable var3
, such that if a condition is met, var3
takes 1, if not var3
takes its old value.
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(grep('a', var1)==1, 1, var3))
If I run this code I get the following error
Error in mutate_impl(.data, dots) :
Column `var3` must be length 3 (the number of rows) or one, not 2
The correct answer is
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
My real code is more complicated and I need to var3
to take its old value when the condition evaluates FALSE
, rather than just a singular value (say 0
).
What am I doing wrong here?
r if-statement dplyr mutate
r if-statement dplyr mutate
asked Nov 24 '18 at 23:20
AmazonianAmazonian
22529
22529
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You should use grepl
:
x %>%
mutate(var3 = 0,
var3 = if_else(grepl('a', var1), 1, var3))
Output:
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
The reason is that grep
gives you only indices of true matches, and grepl
outputs TRUE
or FALSE
for each value of the vector, therefore making it possible to use it with ifelse
(and within dataframes in general).
add a comment |
Answer using str_detect:
library(tidyverse)
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(str_detect(var1,'a'), 1, var3))
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463241%2fr-how-to-change-the-value-of-a-variable-based-on-a-condition-using-dplyrmutate%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You should use grepl
:
x %>%
mutate(var3 = 0,
var3 = if_else(grepl('a', var1), 1, var3))
Output:
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
The reason is that grep
gives you only indices of true matches, and grepl
outputs TRUE
or FALSE
for each value of the vector, therefore making it possible to use it with ifelse
(and within dataframes in general).
add a comment |
You should use grepl
:
x %>%
mutate(var3 = 0,
var3 = if_else(grepl('a', var1), 1, var3))
Output:
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
The reason is that grep
gives you only indices of true matches, and grepl
outputs TRUE
or FALSE
for each value of the vector, therefore making it possible to use it with ifelse
(and within dataframes in general).
add a comment |
You should use grepl
:
x %>%
mutate(var3 = 0,
var3 = if_else(grepl('a', var1), 1, var3))
Output:
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
The reason is that grep
gives you only indices of true matches, and grepl
outputs TRUE
or FALSE
for each value of the vector, therefore making it possible to use it with ifelse
(and within dataframes in general).
You should use grepl
:
x %>%
mutate(var3 = 0,
var3 = if_else(grepl('a', var1), 1, var3))
Output:
var1 var2 var3
1 a 2 1
2 b 2 0
3 ab 2 1
The reason is that grep
gives you only indices of true matches, and grepl
outputs TRUE
or FALSE
for each value of the vector, therefore making it possible to use it with ifelse
(and within dataframes in general).
edited Nov 24 '18 at 23:35
answered Nov 24 '18 at 23:26
arg0nautarg0naut
5,3991319
5,3991319
add a comment |
add a comment |
Answer using str_detect:
library(tidyverse)
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(str_detect(var1,'a'), 1, var3))
add a comment |
Answer using str_detect:
library(tidyverse)
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(str_detect(var1,'a'), 1, var3))
add a comment |
Answer using str_detect:
library(tidyverse)
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(str_detect(var1,'a'), 1, var3))
Answer using str_detect:
library(tidyverse)
x = data.frame(var1 = c('a', 'b', 'ab'),
var2 = rep(2,3))
x
x %>%
dplyr::mutate(var3 = 0,
var3 = if_else(str_detect(var1,'a'), 1, var3))
answered Nov 24 '18 at 23:28
Harro CyrankaHarro Cyranka
1,6081614
1,6081614
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463241%2fr-how-to-change-the-value-of-a-variable-based-on-a-condition-using-dplyrmutate%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown