I have a dataframe with several columns and would like to add a new column and name it according to a previous variable. For example:
df <- data.frame("A" = c(1, 2, 3, 4), "B" = c("a", "c", "d", "b"))
Variable <- "C"
This is part of a function where the variable will be changing and rather than each time specifying:
df$C <- NA
I would like a one line that will take the "Variable" to name the additional column
1 Adding new columns. You can add new columns to a dataframe using the $ and assignment <- operators. To do this, just use the df$name notation and assign a new vector of data to it. As you can see, survey has a new column with the name sex with the values we specified earlier.
Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector.
How do I add a column to a DataFrame in R? To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values . Now, this will effectively add your new variable to your dataset.
mutate() creates new columns that are functions of existing variables. It can also modify (if the name is the same as an existing column) and delete columns (by setting their value to NULL ).
Try [
instead of $
:
> df[, Variable] <- NA
> df
A B C
1 1 a NA
2 2 c NA
3 3 d NA
4 4 b NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With