Reputation: 133
I have a function and a string, "ID" is being passed in as a parameter called column. When I try to create a new data frame within the function and set a column name, I use column, but want the new column name to actually be "ID". I am having issues with doing so, as it thinks the column name should be "column" and doesn't access the string ("ID") corresponding.
Here is the function:
f <- function(column) {
new_df <- data.frame(column=c(1,2,3,4,5), names=c("Ana", "Eric", "Bob", "Katy", "Zac"))
return(new_df)
}
print(f(column="ID")
Ideally, I'd want the new data frame to look like:
ID names
1 Ana
2 Eric
3 Bob
4 Katy
5 Zac
Upvotes: 2
Views: 86
Reputation: 887741
Use tibble
and :=
library(tibble)
f <- function(column) {
new_df <- tibble(!!column :=c(1,2,3,4,5),
names=c("Ana", "Eric", "Bob", "Katy", "Zac"))
return(new_df)
}
-testing
> f(column = "ID")
# A tibble: 5 x 2
ID names
<dbl> <chr>
1 1 Ana
2 2 Eric
3 3 Bob
4 4 Katy
5 5 Zac
Or if we are using base R
, then either setNames
or names
assignment would work
f <- function(column) {
new_df <- data.frame(column=c(1,2,3,4,5), names=c("Ana", "Eric", "Bob", "Katy", "Zac"))
names(new_df)[1] <- column
return(new_df)
}
Upvotes: 3