-2

In Stata, variable name can us local function define.

such as local var="longtime"

`var'_2010`

is actually longtime_2010 in Stata

Can R have the same function as local in dataframe.

I have repeat my code in the same step in several dataframes.

But I have to change their names. How can I use the same as Stata. such as

I have var1-10

var1<-left_join(var1_tot,var1_exp)

.....(repeat 10 times)

var10<-left_join(var10_tot,var10_exp)

janeluyip
  • 17
  • 5
  • 2
    It is unclear what you are asking. Can you elaborate and clarify your question? – mhovd Jun 08 '22 at 13:41
  • 1
    Locals is not a general concept, it is just what Stata calls non-dataset/datafram variables with a short scope. I think your question is "Can column names in a dataframe be assigned dynamically?". If so, does this answer your question: https://stackoverflow.com/questions/33489395/how-to-append-names-to-column-names-of-the-output-data-frame-in-r – TheIceBear Jun 08 '22 at 13:45
  • in Stata a local macro (not function) is a container for a text string, which could be the name of a variable -- or several such names. Again, a variable in Stata is in other terms a column in a dataset. – Nick Cox Jun 08 '22 at 13:52
  • @NickCox Can I container for a text string, to name my data frame in R as stata? – janeluyip Jun 08 '22 at 13:57
  • 1
    It is technically possible in R using `assign` and `get`, but R has better alternatives: [Use a list of data frames](https://stackoverflow.com/a/24376207/903061). – Gregor Thomas Jun 08 '22 at 13:57

2 Answers2

1

Normally if you have associated objects they are put into a list and then one can iterate over the lists. Questions on SO are supposed to have complete reproducible input. Please read the info at the top of the tag page regarding asking questions.

In the absence of that we will provide L1 and L2 below based on the built in BOD data frame. Each of these is a list of 3 data frames but could have been 10 data frames.

library(dplyr)

L1 <- list(BOD, 2*BOD, 3*BOD)
L2 <- list(2*cbind(BOD[1], x = 1:6), 3*cbind(BOD[1], x = 1:6), 4*cbind(BOD[1], x = 1:6))

L3 <- Map(left_join, L1, L2)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

Let's say you have 10 data frames var1_tot, var2_tot, ... var10_tot, and another 10 data frames var1_exp, var2_exp, ... var10_exp, and you want to left join each of these pairwise. You can do this, using get within lapply() as follows. This will return a list of 10 dataframes, the first being var1_tot left-joined with var1_exp, the second being var2_tot left-joined with var2_exp, etc.

lapply(1:10, \(v) {
  dfs = paste0("var",v,c("_tot", "_exp"))
  dplyr::left_join(get(dfs[1]), get(dfs[2]))
})
langtang
  • 22,248
  • 1
  • 12
  • 27