variable problem

Hi :slight_smile: , I want to use variable name (string variable) after $ to extract data from dataset, like below. I don't even know if it's possible. Is it possible or can I change something to do this?

var_name <-  'name'
data$var_name

You can do something like this

xx <- "wday"

dd <- paste0("dat1$",xx)
1 Like
var_name <-  'name'
data[[var_name]]
1 Like

@nirgrahamuk beat me again. My example was supposed to be:

df1 <- data.frame(
  name=c("john","mary"),
  age= c(8,9)
)

var_name <-  'name'
df1$var_name # will not work as expected: no var_name column in df1
#> NULL
str(df1[var_name])
#> 'data.frame':    2 obs. of  1 variable:
#>  $ name: chr  "john" "mary"
str(df1[[var_name]])
#>  chr [1:2] "john" "mary"
Created on 2023-03-10 with reprex v2.0.2
1 Like

Thank you very much. I use your solution. It works! :smiley:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.