Reputation: 1
I was wondering if there is a possibility to add list elements as columns of a data frame.
e.g. I have defined a list
a <- c(1, 2, 3, 4, 5)
and I would like to add it as the columns of my data frame
df <- data.frame(matrix(ncol = 3, nrow = 2500))
x <- c("P", "B", "R")
colnames(df) <- x
My data frame has already values included in columns P, B & R.
Now I would like to add my list a as new columns without any values (alternative it could also be 0) in each of the rows.
In the end my data frame should have the columns P, B, R, 1, 2, 3, 4, 5.
I was thinking about doing it with 'cbind()' or addressing the data frame directly but this does not seem to work. Can anyone please help me on that?
Upvotes: 0
Views: 723
Reputation: 887851
We can also wrap with paste0
to convert to character
df[paste0(a)] <- NA
An option with add_column
library(tibble)
add_column(df, !!! setNames(rep(list(NA), length(a)), a))
We can specify the .after
or .before
to add the columns in a specific location.
Upvotes: 2
Reputation: 33603
You could do:
df[as.character(a)] <- NA
> head(df)
P B R 1 2 3 4 5
1 NA NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA NA
4 NA NA NA NA NA NA NA NA
5 NA NA NA NA NA NA NA NA
6 NA NA NA NA NA NA NA NA
Just note that having column names starting with a number is not good practice.
Upvotes: 2
Reputation: 102625
I think the approach by @sindri_baldur is sufficiently simple already.
Here is another base R option but a bit more complicated
cbind(df,setNames(rep(list(NA),length(a)),a))
Upvotes: 0