Jeni
Jeni

Reputation: 958

Cannot use a variable named with numbers in R

I have some dataframes named as:

1_patient
2_patient
3_patient

Now I am not able to access its variables. For example:

I am not able to obtain:

2_patient$age

If I press tab when writing the name, it automatically gets quoted, but I am still unable to use it.

Do you know how can I solve this?

Upvotes: 1

Views: 66

Answers (1)

akrun
akrun

Reputation: 887028

It is not recommended to name an object with numbers as prefix, but we can use backquote to extract the value from the object

`1_patient`$age

If there are more than object, we can use mget to return the objects in a list and then extract the 'age' column by looping over the list with lapply

mget(ls(pattern = "^\\d+_mtcars$"))
#$`1_mtcars`
#                mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
#Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4


lapply(mget(ls(pattern = "^\\d+_patient$")), `[[`, 'age')

Using a small reproducible example

data(mtcars)
`1_mtcars` <- head(mtcars, 2)
1_mtcars$mpg

Error: unexpected input in "1_"

`1_mtcars`$mpg
#[1] 21 21

Upvotes: 1

Related Questions