0

I'm working on a R-Script where I have to create multiple variables for multiple existing dataframes. For example: I got the three dataframes AAA, BBB and CCC, and each one of them has a column named "height". I would like to get this:

AAA_Skal <- mean(AAA$height) / 6
BBB_Skal <- mean(BBB$height) / 6
CCC_Skal <- mean(CCC$height) / 6

without actually writing a entire line of code for each dataframe. (The reason for this is that I got more than just 3 dataframes and I have to proceed a lot of code with them).

What I tried is the following:

dfs <- c("AAA", "BBB", "CCC")

Skal <- function(x) {
sprintf("%s_Skal", dfs[x]) <- mean(sprintf("%s_$height", dfs[x])) / 6
}

I should then be able to type Skal(1) to get

AAA_Skal <- mean(AAA$height) / 6

First I thought it isnt working because sprintf gives "AAA" as an output, with quotation marks. So I tried as.name(sprintf()), but it doesent work either. I hope someone can help me on this issue, and sorry for my bad english.

0

1 Answer 1

3

You can use assign and get

AAA <- data.frame(x = letters[1:10], height = rnorm(10))
BBB <- data.frame(y = sample(20:60, 10), height = rnorm(10, 5))
CCC <- data.frame(z = rbinom(10, 5, .2), height = rnorm(10, 50))

dfs <- c("AAA", "BBB", "CCC")

x <- 1
assign(sprintf("%s_Skal", dfs[x]), mean(get(dfs[x])$height) / 6)
AAA_Skal
## [1] -0.02807432

But I would recommend storing your data.frames in a list so you can do something like

l <- list(AAA, BBB, CCC)
sapply(l, function(x) mean(x$height) / 6 )
## [1] -0.02807432  0.84785430  8.38655123
Sign up to request clarification or add additional context in comments.

3 Comments

Dear @JakeBurkhead Maybe could it get the same result using lapply(l, function(x) mean(x$height) / 6 ) what is the difference between lapply() and sapply()
@Duck lapply will return a list of length 1 numeric vectors (try it out and see!). sapply tries to coerce its output into a vector or matrix and names it output, lapply will always return a list. sapply(..., simplify = FALSE, USE.NAMES = FALSE) is equivalent to lapply. See ?sapply for more info.
Ok @JakeBurkhead sapply() is more practical than lapply() and it gives me a more clean solution than lapply that gives a list as result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.