I would like to create a two-column data frame. The first column contains only one letter, while the second column contains several letters. The content in the second column is stored in a vector. I tried to use the tibble function from the tibble package, but it gave me strange results. The second column is the same as the first column.
library(tibble)
vec <- c("A", "B", "C")
tibble(
vec = rep(vec[1], length(vec)),
vec_new = vec
)
# # A tibble: 3 x 2
# vec vec_new
# <chr> <chr>
# 1 A A
# 2 A A
# 3 A A
I tried to create the same data frame with the data.frame and data.table functions from the data.table package. The result is as expected. Please let me know why tibble generates strange results and what is the best way to fix it.
data.frame(
vec = rep(vec[1], length(vec)),
vec_new = vec
)
# vec vec_new
# 1 A A
# 2 A B
# 3 A C
library(data.table)
data.table(
vec = rep(vec[1], length(vec)),
vec_new = vec
)
# vec vec_new
# 1: A A
# 2: A B
# 3: A C
CodePudding user response:
You could use the 'bang bang' notation to refer to objects outside of your tibble to prevent the 'issue' @Gregor Thomas mentioned in the comment of your post.
library(tibble)
tibble(vec = rep(vec[1], length(vec)),
vec_new = !!vec)
# A tibble: 3 x 2
vec vec_new
<chr> <chr>
1 A A
2 A B
3 A C
CodePudding user response:
There is a .env argument which can be used
library(tibble)
tibble(
vec = rep(vec[1], length(vec)),
vec_new = .env$vec
)
# A tibble: 3 × 2
vec vec_new
<chr> <chr>
1 A A
2 A B
3 A C
