Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new column in r dataframe with a constant number?

Tags:

dataframe

r

How can I create a new column containing a constant value like 100?

Example: Number 100 100 100 100

like image 640
Mahan Avatar asked Sep 03 '25 03:09

Mahan


1 Answers

With dplyr, you can use mutate and assign a constant number to a new variable. If you only provide one number (like 100 below), then each row will be filled in with that given number.

library(dplyr)

df %>%
  mutate(newCol = 100)

Output

    x newCol
1   1    100
2   2    100
3   3    100
4   4    100
5   5    100
6   6    100
7   7    100
8   8    100
9   9    100
10 10    100

Or in base R, you can create a copy of the dataframe, then create the new column:

df2 <- df
df2$Number <- 100

Data

df <- data.frame(x = c(1:10))
like image 195
AndrewGB Avatar answered Sep 05 '25 01:09

AndrewGB