Noob here with an R assignment due in a few hours. Can anyone give me a simple command for renaming variables in a two-column data frame and adding a new variable to that data frame? Thanks so much!
1 Like
If you're using base R, you can do it like this:
mydata = data.frame(red = 1:5, blue = 6:10)
mydata$yellow = mydata$red # copies the old column
mydata$red = NULL # deletes the old column
mydata$green = 11:15 # adds another column
If you're using the tidyverse, you can use mutate
to add new columns (or overwrite existing ones), and you can either rename
or select
with named arguments to rename columns:
library(tidyverse)
mydata %>%
mutate(green = 11:15) %>%
select(purple = blue, yellow, green) # selects the blue, yellow and green columns (but blue is renamed to purple)
Hope that helps!
3 Likes