0
votes

I'm new to R and am trying to work with a relatively large data frame. I am trying to reduce a large data frame to just the variables I need. I kind of figured out how to do that with data.frame function. However, is there a way to change the variable names in the same step?

Example below:

Say my existing dataset has 10 variables (columns): Var1, var2, var3... I only want to leave first 2 variables. So i write:

small_data <- data.frame(var1, var2)

So the question is can i somehow change the names of the variables within that data.frame function?

3

3 Answers

3
votes

You could do it like this:

> var1 <- runif(5)
> var2 <- runif(5)
> data.frame(new.name1 = var1, new.name2 = var2)
  new.name1  new.name2
1 0.9658143 0.16985282
2 0.2662441 0.37762692
3 0.1374154 0.04857553
4 0.7738637 0.05170524
5 0.1480800 0.67682980

> x <- data.frame(new.name1 = var1, new.name2 = var2)
> colnames(x) <- c("old.name1", "old.name2")
> x
  old.name1  old.name2
1 0.9658143 0.16985282
2 0.2662441 0.37762692
3 0.1374154 0.04857553
4 0.7738637 0.05170524
5 0.1480800 0.67682980
1
votes

You can do this in one line.

small_data <- with(big_data, data.frame(var1_new=var1,var2_new=var2))
0
votes
small <- bigger[ , 1:2]
names(small) <- c("firstnm", "secndnm")