How to Get Name of Variable in R (Substitute)

How to get name of variable in R (substitute)?

I suggest you consider passing optional name value to these functions. I say this because it seems like you really want to use the name as a label for something in the end result; so it's not really the variable itself that matters so much as its name. You could do

fun1 <- function (some_variable, name=deparse(substitute(some_variable))) {
name
}
fun2 <- function (var_pass, name=deparse(substitute(var_pass))) {
fun1 (var_pass, name)
}
my_var <- c(1,2)

fun2(my_var)
# [1] "my_var"

fun1(my_var)
# [1] "my_var"

This way if you end up having some odd variable name and what to give a better name to a result, you at least have the option. And by default it should do what you want without having to require the name parameter.

How to read a list of variable names and substitute them in a function in R?

You can use as.formula to convert text to valid R formulas. (But as you are discovering you cannot use R formulas as macros.) I also used just the varlist items as the loop variables rather than sequential integers.

Dataset <- iris
varlist <- data.frame("Sepal.Length", "Sepal.Width", "Petal.Length")
for (i in varlist ){ form <- as.formula( paste( i, "~ Petal.Width"))
model <- lm(form, data = Dataset)
printing <- data.frame(i = model$coefficients['Petal.Width'])
write.csv(printing,paste0("~/Desktop/",i,"PetalWidthSlope.csv"))
}

I now have 3 more files on my Desktop:

Sample Image

R - How to replace values of a variable with the name of the variable in dplyr

If we need to replace the 1 with the column names and 0 by blank (""), and if the columns are only binary, we can use map2 to loop through the columns and corresponding column names, then add 1 to the columns and use it as index to replace the 1 with "" and 2 with the corresponding column names

library(tidyverse)
map2_df(df, colnames(df), ~ c('', .y)[.x +1])
# A tibble: 2 x 2
# a b
# <chr> <chr>
#1 "" b
#2 a ""

How to get the name of variable in NSE with dplyr

Use ensym() from rlang:

require("dplyr")
require("rlang")
test <- function(var){
mtcars %>% select({{var}})
print(ensym(var))
}

test(wt)
#>wt

as.character(test(wt))
#>wt
#>[1] "wt"

How to get the name of a variable as a string in a loop?

The 'myobjects' contain only the values of the objects 'a', 'b', 'c'. If we need to get the original objects, create a named vector and get the names

myobjects <- c(a = a, b = b, c = c)
for(i in 1:3) cat(names(myobjects[i]), " : ", myobjects[i], "\n")
#a : 5
#b : 6
#c : 7

Or as @IceCreamToucan mentioned in the comments, it can be vectorized (without a for looop) as paste does vectorization

cat(paste0(names(myobjects), ' : ', myobjects), '\n', sep = '\n')

Get name of variable passed as function parameter

Perhaps decorate that variable with a "comment" attribute in another function? Note that the variable you want to decorate has to be wrapped directly in the decoration function z; otherwise, an error is raised (by design and for robustness).

example_fun <- function(x){
attr(x, "comment")
}

z <- function(x) {
nm <- substitute(x)
nm <- as.character(
if (is.symbol(nm) && !identical(nm, quote(.))) {
nm
} else if (length(nm) > 1L && (identical(nm[[1L]], quote(`[[`)) || identical(nm[[1L]], quote(`$`)))) {
tail(nm, 1L)
} else {
stop("not a valid symbol or extract operator.", call. = match.call())
}
)
`comment<-`(x, nm)
}

Output

> example_fun(z(df$noi))
[1] "noi"
> z(df$noi) %>% (function(x) x + 1) %>% example_fun()
[1] "noi"
> df %>% mutate(example_fun(z(noi)))
noi example_fun(z(noi))
1 1 noi
2 2 noi
3 3 noi
> z(df[["noi"]]) %>% example_fun()
[1] "noi"
> with(df, z(noi)) %>% example_fun()
[1] "noi"
> z(with(df, noi)) %>% example_fun()
Error in z(with(df, noi)) : not a valid symbol or extract operator.
> df$noi %>% z()
Error in z(.) : not a valid symbol or extract operator.

... but this may not be a robust method. It is extremely difficult to achieve what you want in a robust way, especially when a pipeline is involved. I think you should read Hadley's Advanced R and learn more about how bindings and environments work.

R get object name when is input of another function

Can you share your code? I have no problem getting the output.

new_object = 10
new_object
[1] 10

fun1 <- function(fun_input) {
deparse(substitute(fun_input))
}

fun1(new_object)
[1] "new_object"

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

How to replace all variable names with the contents of the first row in a tibble

A possible solution:

df <- structure(list(Subject = c("Subject", "429753", "b952x8", "264062", 
"53082m"), Q1 = c("age", "24", "23", "19", "35"), Q2 = c("gender",
"1", "2", "1", "1"), Q3 = c("cue", "man", "mushroom", "night",
"moon")), row.names = c(NA, -5L), class = "data.frame")

names(df) <- df[1,]
df <- df[-1,]
df

#> Subject age gender cue
#> 2 429753 24 1 man
#> 3 b952x8 23 2 mushroom
#> 4 264062 19 1 night
#> 5 53082m 35 1 moon


Related Topics



Leave a reply



Submit