R - How to dynamically construct a function name in mutate with quasiquotation











up vote
2
down vote

favorite












Firstly it is my first question on StackOverflow, I hope I will write it the good way. If not, don't hesitate to tell me... And sorry for my approximative english!



I would like to use the mutate function from dplyr to change the type of the columns of a data.frame, but without knowing in advance the new type. Thus I would like to create dynamically the function name (for example "as.numeric", "as.factor"), taking the new type from another data.frame.



Here is a concrete example (what I want to do is for data.frames with more than 100 variables, so you will understand I don't want to do this manually!):



library(tidyverse)

df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "Roger", "Steve"
$ Age <chr> "40", "32"

types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)
glimpse(types)

Observations: 2
Variables: 3
$ Field <chr> "Name", "Age"
$ OldType <chr> "character", "character"
$ NewType <chr> "factor", "integer"


I searched during a long time and found a lot of documentation on quasiquotation, and I tried a few things, but without never getting the expected result. Here are two attempts I made:



# First attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- enquo(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- enquo(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "as.factor(Name)", "as.factor(Name)"
$ Age <chr> "as.integer(Age)", "as.integer(Age)"


=> the function calls are considered as strings, and the value of the columns are replaced instead of their types.



# Second attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- ensym(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- ensym(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}


Here I get an error:



Error in mutate_impl(.data, dots) : Binding not found: as.factor(Name).


I guess the mutate function considers what is in parenthesis as a whole variable name?



I have tried other things but without success. I must admit that I am not a R expert and I have difficulties to fully understand this concept of quasiquotation, despite the quality of the documentation. So I know that I am doing the things wrong, but Idon't know why nor how to do it right... Can someone help?



Thanks!










share|improve this question






















  • library(dplyr) , parse_guess will help you , df %mutate_all(parse_guess). It automatically detects the structure of the data frame.
    – Hunaidkhan
    Nov 15 at 11:13












  • Thank you Hunaidkhan, I didn't know this function. I tried it and in some cases it could fit my needs, but not in this one. For example, here, the "Name" field type is let to "character" where I would like to have "factor". And I may want to coerce some character fields into integer: my datas are sometimes not clean and there can be errors - for example a string where I expect an integer - that could make the "parse_guess" function think the variable is string, whereas I want integer - coerce in integer will transofrm the "wrong" strings into NA, and that suits me. But thanks for your answer.
    – jlavadou
    Nov 15 at 12:39

















up vote
2
down vote

favorite












Firstly it is my first question on StackOverflow, I hope I will write it the good way. If not, don't hesitate to tell me... And sorry for my approximative english!



I would like to use the mutate function from dplyr to change the type of the columns of a data.frame, but without knowing in advance the new type. Thus I would like to create dynamically the function name (for example "as.numeric", "as.factor"), taking the new type from another data.frame.



Here is a concrete example (what I want to do is for data.frames with more than 100 variables, so you will understand I don't want to do this manually!):



library(tidyverse)

df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "Roger", "Steve"
$ Age <chr> "40", "32"

types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)
glimpse(types)

Observations: 2
Variables: 3
$ Field <chr> "Name", "Age"
$ OldType <chr> "character", "character"
$ NewType <chr> "factor", "integer"


I searched during a long time and found a lot of documentation on quasiquotation, and I tried a few things, but without never getting the expected result. Here are two attempts I made:



# First attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- enquo(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- enquo(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "as.factor(Name)", "as.factor(Name)"
$ Age <chr> "as.integer(Age)", "as.integer(Age)"


=> the function calls are considered as strings, and the value of the columns are replaced instead of their types.



# Second attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- ensym(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- ensym(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}


Here I get an error:



Error in mutate_impl(.data, dots) : Binding not found: as.factor(Name).


I guess the mutate function considers what is in parenthesis as a whole variable name?



I have tried other things but without success. I must admit that I am not a R expert and I have difficulties to fully understand this concept of quasiquotation, despite the quality of the documentation. So I know that I am doing the things wrong, but Idon't know why nor how to do it right... Can someone help?



Thanks!










share|improve this question






















  • library(dplyr) , parse_guess will help you , df %mutate_all(parse_guess). It automatically detects the structure of the data frame.
    – Hunaidkhan
    Nov 15 at 11:13












  • Thank you Hunaidkhan, I didn't know this function. I tried it and in some cases it could fit my needs, but not in this one. For example, here, the "Name" field type is let to "character" where I would like to have "factor". And I may want to coerce some character fields into integer: my datas are sometimes not clean and there can be errors - for example a string where I expect an integer - that could make the "parse_guess" function think the variable is string, whereas I want integer - coerce in integer will transofrm the "wrong" strings into NA, and that suits me. But thanks for your answer.
    – jlavadou
    Nov 15 at 12:39















up vote
2
down vote

favorite









up vote
2
down vote

favorite











Firstly it is my first question on StackOverflow, I hope I will write it the good way. If not, don't hesitate to tell me... And sorry for my approximative english!



I would like to use the mutate function from dplyr to change the type of the columns of a data.frame, but without knowing in advance the new type. Thus I would like to create dynamically the function name (for example "as.numeric", "as.factor"), taking the new type from another data.frame.



Here is a concrete example (what I want to do is for data.frames with more than 100 variables, so you will understand I don't want to do this manually!):



library(tidyverse)

df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "Roger", "Steve"
$ Age <chr> "40", "32"

types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)
glimpse(types)

Observations: 2
Variables: 3
$ Field <chr> "Name", "Age"
$ OldType <chr> "character", "character"
$ NewType <chr> "factor", "integer"


I searched during a long time and found a lot of documentation on quasiquotation, and I tried a few things, but without never getting the expected result. Here are two attempts I made:



# First attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- enquo(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- enquo(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "as.factor(Name)", "as.factor(Name)"
$ Age <chr> "as.integer(Age)", "as.integer(Age)"


=> the function calls are considered as strings, and the value of the columns are replaced instead of their types.



# Second attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- ensym(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- ensym(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}


Here I get an error:



Error in mutate_impl(.data, dots) : Binding not found: as.factor(Name).


I guess the mutate function considers what is in parenthesis as a whole variable name?



I have tried other things but without success. I must admit that I am not a R expert and I have difficulties to fully understand this concept of quasiquotation, despite the quality of the documentation. So I know that I am doing the things wrong, but Idon't know why nor how to do it right... Can someone help?



Thanks!










share|improve this question













Firstly it is my first question on StackOverflow, I hope I will write it the good way. If not, don't hesitate to tell me... And sorry for my approximative english!



I would like to use the mutate function from dplyr to change the type of the columns of a data.frame, but without knowing in advance the new type. Thus I would like to create dynamically the function name (for example "as.numeric", "as.factor"), taking the new type from another data.frame.



Here is a concrete example (what I want to do is for data.frames with more than 100 variables, so you will understand I don't want to do this manually!):



library(tidyverse)

df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "Roger", "Steve"
$ Age <chr> "40", "32"

types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)
glimpse(types)

Observations: 2
Variables: 3
$ Field <chr> "Name", "Age"
$ OldType <chr> "character", "character"
$ NewType <chr> "factor", "integer"


I searched during a long time and found a lot of documentation on quasiquotation, and I tried a few things, but without never getting the expected result. Here are two attempts I made:



# First attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- enquo(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- enquo(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <chr> "as.factor(Name)", "as.factor(Name)"
$ Age <chr> "as.integer(Age)", "as.integer(Age)"


=> the function calls are considered as strings, and the value of the columns are replaced instead of their types.



# Second attempt
for(i in 1:nrow(types)){
field <- types$Field[i]
field_quo <- ensym(field)
new_type <- paste0("as.", types$NewType[i], "(", field, ")")
new_type_quo <- ensym(new_type)
df <- df %>% mutate(!!field_quo := !!new_type_quo)
}


Here I get an error:



Error in mutate_impl(.data, dots) : Binding not found: as.factor(Name).


I guess the mutate function considers what is in parenthesis as a whole variable name?



I have tried other things but without success. I must admit that I am not a R expert and I have difficulties to fully understand this concept of quasiquotation, despite the quality of the documentation. So I know that I am doing the things wrong, but Idon't know why nor how to do it right... Can someone help?



Thanks!







r dplyr






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 at 11:02









jlavadou

133




133












  • library(dplyr) , parse_guess will help you , df %mutate_all(parse_guess). It automatically detects the structure of the data frame.
    – Hunaidkhan
    Nov 15 at 11:13












  • Thank you Hunaidkhan, I didn't know this function. I tried it and in some cases it could fit my needs, but not in this one. For example, here, the "Name" field type is let to "character" where I would like to have "factor". And I may want to coerce some character fields into integer: my datas are sometimes not clean and there can be errors - for example a string where I expect an integer - that could make the "parse_guess" function think the variable is string, whereas I want integer - coerce in integer will transofrm the "wrong" strings into NA, and that suits me. But thanks for your answer.
    – jlavadou
    Nov 15 at 12:39




















  • library(dplyr) , parse_guess will help you , df %mutate_all(parse_guess). It automatically detects the structure of the data frame.
    – Hunaidkhan
    Nov 15 at 11:13












  • Thank you Hunaidkhan, I didn't know this function. I tried it and in some cases it could fit my needs, but not in this one. For example, here, the "Name" field type is let to "character" where I would like to have "factor". And I may want to coerce some character fields into integer: my datas are sometimes not clean and there can be errors - for example a string where I expect an integer - that could make the "parse_guess" function think the variable is string, whereas I want integer - coerce in integer will transofrm the "wrong" strings into NA, and that suits me. But thanks for your answer.
    – jlavadou
    Nov 15 at 12:39


















library(dplyr) , parse_guess will help you , df %mutate_all(parse_guess). It automatically detects the structure of the data frame.
– Hunaidkhan
Nov 15 at 11:13






library(dplyr) , parse_guess will help you , df %mutate_all(parse_guess). It automatically detects the structure of the data frame.
– Hunaidkhan
Nov 15 at 11:13














Thank you Hunaidkhan, I didn't know this function. I tried it and in some cases it could fit my needs, but not in this one. For example, here, the "Name" field type is let to "character" where I would like to have "factor". And I may want to coerce some character fields into integer: my datas are sometimes not clean and there can be errors - for example a string where I expect an integer - that could make the "parse_guess" function think the variable is string, whereas I want integer - coerce in integer will transofrm the "wrong" strings into NA, and that suits me. But thanks for your answer.
– jlavadou
Nov 15 at 12:39






Thank you Hunaidkhan, I didn't know this function. I tried it and in some cases it could fit my needs, but not in this one. For example, here, the "Name" field type is let to "character" where I would like to have "factor". And I may want to coerce some character fields into integer: my datas are sometimes not clean and there can be errors - for example a string where I expect an integer - that could make the "parse_guess" function think the variable is string, whereas I want integer - coerce in integer will transofrm the "wrong" strings into NA, and that suits me. But thanks for your answer.
– jlavadou
Nov 15 at 12:39














2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










interesting question. I think I found a solution using map2 from purrr package in tidyverse.



# Data
df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)

library(tidyverse)

# Create a column with function names that is needed. I.e. adding as.
types <- types %>%
mutate(newType2 = paste0("as.", NewType))

# Then loop over column names and functions
df2 <- map2_dfc(types$Field,
types$newType2,
~df %>%
select_(.x) %>%
mutate_all(.y)
) %>% as_tibble()


gives you



> df2
# A tibble: 2 x 2
Name Age
<fct> <int>
1 Roger 40
2 Steve 32


But for easy data type conversion try. which gives you a suitable data type for each column. However, it never suggests factors. But then you can use convert if you want.



library(hablar)

df %>%
retype() %>%
convert(fct(Name))





share|improve this answer























  • Thanks davsjob, that's perfect! And more rapid as a for loop (I have tested your solution against a for loop (using taiki-sakai's solution) with a large dataset, it was the fastet).
    – jlavadou
    Nov 19 at 11:59


















up vote
0
down vote













I think what you want is get. This allows you to retrieve an object by passing in its name as a character, so get('as.factor') will return the as.factor function. Fitting this into your previous attempts:



for(i in 1:nrow(types)) {
field <- sym(types$Field[i])
typeFun <- get(paste0('as.', types$NewType[i]))
df <- df %>%
mutate(!!field := typeFun(!!field))
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <fct> Roger, Steve
$ Age <int> 40, 32





share|improve this answer























  • Thanks @taiki-sakai, function "get" was exactly what I was looking for in the context of using a for loop! This works great. I won't accept your answer as the best solution because davsjob's solution below seems better to me (and more rapid after some tests), but I will keep yours in mind for the future!
    – jlavadou
    Nov 19 at 11:57











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',
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
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53318004%2fr-how-to-dynamically-construct-a-function-name-in-mutate-with-quasiquotation%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








up vote
0
down vote



accepted










interesting question. I think I found a solution using map2 from purrr package in tidyverse.



# Data
df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)

library(tidyverse)

# Create a column with function names that is needed. I.e. adding as.
types <- types %>%
mutate(newType2 = paste0("as.", NewType))

# Then loop over column names and functions
df2 <- map2_dfc(types$Field,
types$newType2,
~df %>%
select_(.x) %>%
mutate_all(.y)
) %>% as_tibble()


gives you



> df2
# A tibble: 2 x 2
Name Age
<fct> <int>
1 Roger 40
2 Steve 32


But for easy data type conversion try. which gives you a suitable data type for each column. However, it never suggests factors. But then you can use convert if you want.



library(hablar)

df %>%
retype() %>%
convert(fct(Name))





share|improve this answer























  • Thanks davsjob, that's perfect! And more rapid as a for loop (I have tested your solution against a for loop (using taiki-sakai's solution) with a large dataset, it was the fastet).
    – jlavadou
    Nov 19 at 11:59















up vote
0
down vote



accepted










interesting question. I think I found a solution using map2 from purrr package in tidyverse.



# Data
df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)

library(tidyverse)

# Create a column with function names that is needed. I.e. adding as.
types <- types %>%
mutate(newType2 = paste0("as.", NewType))

# Then loop over column names and functions
df2 <- map2_dfc(types$Field,
types$newType2,
~df %>%
select_(.x) %>%
mutate_all(.y)
) %>% as_tibble()


gives you



> df2
# A tibble: 2 x 2
Name Age
<fct> <int>
1 Roger 40
2 Steve 32


But for easy data type conversion try. which gives you a suitable data type for each column. However, it never suggests factors. But then you can use convert if you want.



library(hablar)

df %>%
retype() %>%
convert(fct(Name))





share|improve this answer























  • Thanks davsjob, that's perfect! And more rapid as a for loop (I have tested your solution against a for loop (using taiki-sakai's solution) with a large dataset, it was the fastet).
    – jlavadou
    Nov 19 at 11:59













up vote
0
down vote



accepted







up vote
0
down vote



accepted






interesting question. I think I found a solution using map2 from purrr package in tidyverse.



# Data
df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)

library(tidyverse)

# Create a column with function names that is needed. I.e. adding as.
types <- types %>%
mutate(newType2 = paste0("as.", NewType))

# Then loop over column names and functions
df2 <- map2_dfc(types$Field,
types$newType2,
~df %>%
select_(.x) %>%
mutate_all(.y)
) %>% as_tibble()


gives you



> df2
# A tibble: 2 x 2
Name Age
<fct> <int>
1 Roger 40
2 Steve 32


But for easy data type conversion try. which gives you a suitable data type for each column. However, it never suggests factors. But then you can use convert if you want.



library(hablar)

df %>%
retype() %>%
convert(fct(Name))





share|improve this answer














interesting question. I think I found a solution using map2 from purrr package in tidyverse.



# Data
df <- data.frame(Name = c("Roger", "Steve"), Age = c("40", "32"), stringsAsFactors = FALSE)
types <- data.frame(Field = c("Name", "Age"), OldType = c("character", "character"), NewType = c("factor", "integer"), stringsAsFactors = FALSE)

library(tidyverse)

# Create a column with function names that is needed. I.e. adding as.
types <- types %>%
mutate(newType2 = paste0("as.", NewType))

# Then loop over column names and functions
df2 <- map2_dfc(types$Field,
types$newType2,
~df %>%
select_(.x) %>%
mutate_all(.y)
) %>% as_tibble()


gives you



> df2
# A tibble: 2 x 2
Name Age
<fct> <int>
1 Roger 40
2 Steve 32


But for easy data type conversion try. which gives you a suitable data type for each column. However, it never suggests factors. But then you can use convert if you want.



library(hablar)

df %>%
retype() %>%
convert(fct(Name))






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 15 at 16:56

























answered Nov 15 at 16:50









davsjob

50726




50726












  • Thanks davsjob, that's perfect! And more rapid as a for loop (I have tested your solution against a for loop (using taiki-sakai's solution) with a large dataset, it was the fastet).
    – jlavadou
    Nov 19 at 11:59


















  • Thanks davsjob, that's perfect! And more rapid as a for loop (I have tested your solution against a for loop (using taiki-sakai's solution) with a large dataset, it was the fastet).
    – jlavadou
    Nov 19 at 11:59
















Thanks davsjob, that's perfect! And more rapid as a for loop (I have tested your solution against a for loop (using taiki-sakai's solution) with a large dataset, it was the fastet).
– jlavadou
Nov 19 at 11:59




Thanks davsjob, that's perfect! And more rapid as a for loop (I have tested your solution against a for loop (using taiki-sakai's solution) with a large dataset, it was the fastet).
– jlavadou
Nov 19 at 11:59












up vote
0
down vote













I think what you want is get. This allows you to retrieve an object by passing in its name as a character, so get('as.factor') will return the as.factor function. Fitting this into your previous attempts:



for(i in 1:nrow(types)) {
field <- sym(types$Field[i])
typeFun <- get(paste0('as.', types$NewType[i]))
df <- df %>%
mutate(!!field := typeFun(!!field))
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <fct> Roger, Steve
$ Age <int> 40, 32





share|improve this answer























  • Thanks @taiki-sakai, function "get" was exactly what I was looking for in the context of using a for loop! This works great. I won't accept your answer as the best solution because davsjob's solution below seems better to me (and more rapid after some tests), but I will keep yours in mind for the future!
    – jlavadou
    Nov 19 at 11:57















up vote
0
down vote













I think what you want is get. This allows you to retrieve an object by passing in its name as a character, so get('as.factor') will return the as.factor function. Fitting this into your previous attempts:



for(i in 1:nrow(types)) {
field <- sym(types$Field[i])
typeFun <- get(paste0('as.', types$NewType[i]))
df <- df %>%
mutate(!!field := typeFun(!!field))
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <fct> Roger, Steve
$ Age <int> 40, 32





share|improve this answer























  • Thanks @taiki-sakai, function "get" was exactly what I was looking for in the context of using a for loop! This works great. I won't accept your answer as the best solution because davsjob's solution below seems better to me (and more rapid after some tests), but I will keep yours in mind for the future!
    – jlavadou
    Nov 19 at 11:57













up vote
0
down vote










up vote
0
down vote









I think what you want is get. This allows you to retrieve an object by passing in its name as a character, so get('as.factor') will return the as.factor function. Fitting this into your previous attempts:



for(i in 1:nrow(types)) {
field <- sym(types$Field[i])
typeFun <- get(paste0('as.', types$NewType[i]))
df <- df %>%
mutate(!!field := typeFun(!!field))
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <fct> Roger, Steve
$ Age <int> 40, 32





share|improve this answer














I think what you want is get. This allows you to retrieve an object by passing in its name as a character, so get('as.factor') will return the as.factor function. Fitting this into your previous attempts:



for(i in 1:nrow(types)) {
field <- sym(types$Field[i])
typeFun <- get(paste0('as.', types$NewType[i]))
df <- df %>%
mutate(!!field := typeFun(!!field))
}
glimpse(df)

Observations: 2
Variables: 2
$ Name <fct> Roger, Steve
$ Age <int> 40, 32






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 15 at 17:01

























answered Nov 15 at 16:56









Taiki Sakai

34114




34114












  • Thanks @taiki-sakai, function "get" was exactly what I was looking for in the context of using a for loop! This works great. I won't accept your answer as the best solution because davsjob's solution below seems better to me (and more rapid after some tests), but I will keep yours in mind for the future!
    – jlavadou
    Nov 19 at 11:57


















  • Thanks @taiki-sakai, function "get" was exactly what I was looking for in the context of using a for loop! This works great. I won't accept your answer as the best solution because davsjob's solution below seems better to me (and more rapid after some tests), but I will keep yours in mind for the future!
    – jlavadou
    Nov 19 at 11:57
















Thanks @taiki-sakai, function "get" was exactly what I was looking for in the context of using a for loop! This works great. I won't accept your answer as the best solution because davsjob's solution below seems better to me (and more rapid after some tests), but I will keep yours in mind for the future!
– jlavadou
Nov 19 at 11:57




Thanks @taiki-sakai, function "get" was exactly what I was looking for in the context of using a for loop! This works great. I won't accept your answer as the best solution because davsjob's solution below seems better to me (and more rapid after some tests), but I will keep yours in mind for the future!
– jlavadou
Nov 19 at 11:57


















draft saved

draft discarded




















































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.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


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




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53318004%2fr-how-to-dynamically-construct-a-function-name-in-mutate-with-quasiquotation%23new-answer', 'question_page');
}
);

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







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents