1

I'm looking for a way to loop through a list of variables that are data and bind them into a single data frame, this will allow me to store the data in the script rather than a separate file. Below is my unsuccessful attemp where I'm now sure what function I need to use to get variable prefixed with "p" to be recognised correctly in the loop.

# Data 

p1 <- c(518458.9470, 6479704.947, 1890.820847)
p2 <- c(518480.0626, 6479701.156, 1890.193591)
p3 <- c(518499.0065, 6479711.374, 1886.774569)

# Create data frame

for (i in 1:3){
  if (i = 1){
    d <- paste0("p",i)
  }else{
    df <- rbind(df, paste("p",i))
  } 
}

3 Answers 3

3

You can use mget to do this without a loop.

data.frame(mget(paste0('p', 1:3)))

#         p1        p2        p3
#1  518458.9  518480.1  518499.0
#2 6479704.9 6479701.2 6479711.4
#3    1890.8    1890.2    1886.8
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using a transpose to get the data frame shape I wanted... t(data.frame(mget(paste0('p', 1:3))))
1

In the spirit of your original code, you can get() those variable values by name:

data <- c()
for (i in 1:3) {
    name <- paste0('p', i)
    data <- rbind(data, get(name))
}
A matrix: 3 × 3 of type dbl
518458.9  6479705  1890.821
518480.1  6479701  1890.194
518499.0  6479711  1886.775

1 Comment

I was looking for a data frame as the final output so was easy to change the last line to ... data <- rbind(data, get(name)). Like the way you just used an empty set was used to initialize the variable to be bound to rather than having and if statement
0

Just df <- data.frame(rbind(p1, p2, p3)) should do the job, if I've understood your question correctly.

If those are the only data variables you have, I would skip the middle step of defining the variables and just do

df <- data.frame(
    p1 = c(518458.9470, 6479704.947, 1890.820847),
    p2 = c(518480.0626, 6479701.156, 1890.193591),
    p3 = c(518499.0065, 6479711.374, 1886.774569)
)

It all depends on where your data initially comes from, really.

4 Comments

Correct but in practice I have more than three lines of data so loop solution is what I am looking for
Alright, then am I correct in assuming your data is defined in another way than just p1 <- c(...) etc?
Yes ... the solution above using mget seems the best and avoid the need for a explicit loop
In that case I agree.

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.