Initialize an empty tibble with column names and 0 rows
Since you want to combine a list of tibbles. You can just assign NULL to the variable and then bind_rows
with other tibbles.
res = NULL
for(i in tibbleList)
res = bind_rows(res,i)
However, a much efficient way to do this is
bind_rows(tibbleList) # combine all tibbles in the list
Create empty tibble/data frame with column names coming from a vector
You can create a named vector, vec
, where the first argument sets the type of column you want. The rep("", 3)
line says I want three character columns. Then the second argument is the vector of column names.
Use dplyr::bind_rows
to convert this into tibble with one row. Then [0, ]
selects zero rows, leaving it empty.
With this method, you can control the data type for each column easily.
library(dplyr)
vec <- setNames(rep("", 3), letters[1:3])
bind_rows(vec)[0, ]
# A tibble: 0 x 3
# ... with 3 variables: a <chr>, b <chr>, c <chr>
You can also use as_tibble
if you transpose the named vector. I guess I use bind_rows
because I usually have dplyr
loaded but not tibble
.
library(tibble)
vec <- setNames(rep("", 3), letters[1:3])
as_tibble(t(vec))[0, ]
# A tibble: 0 x 3
# ... with 3 variables: a <chr>, b <chr>, c <chr>
If you know all of the columns are of a single type (e.g., character), you can do something like this.
vec <- letters[1:3]
df <- bind_rows(setNames(rep("", length(vec)), vec))[0, ]
Create a data frame from vector, using the values as columns
If you're a tidyverse fan as I see by your using of tibble
, you could use a combination of map_dfc
and setNames
:
library(tidyverse)
df <- x %>% map_dfc(setNames, object = list(character(1)))
df
# A tibble: 1 x 3
`1` `2` `3`
<chr> <chr> <chr>
1 "" "" ""
In an empty tibble, column types change depending on how the first row is added
Here you concatenate in an atomic vector:
newValues <- c("W"="Testing...", "X"=pi, "Y"=TRUE, "Z"=as.Date("2020-04-29"))
An atomic vector contains elements of the same mode, so everything is coerced to character mode:
> newValues
W X Y Z
"Testing..." "3.14159265358979" "TRUE" "18381"
Use a list instead:
newValues <- list("W"="Testing...", "X"=pi, "Y"=TRUE, "Z"=as.Date("2020-04-29"))
(and then use newValues[[f]]
).
Create empty data frame with column names by assigning a string vector?
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
Create empty columns with mutate, column names from a vector
It's probably not really in the spirit of the tidyverse, but you can do
df %>% mutate(`[<-`(df, sn, value = NA))
#> pseudonym sn01 sn02 sn03
#> 1 a NA NA NA
#> 2 b NA NA NA
#> 3 c NA NA NA
#> 4 d NA NA NA
Can I create a tibble with 1 row and 11 columns in R from a data frame with 0 rows and 0 columns?
You can try :
#get index of dataframes that has 0 columns
inds <- lengths(list_data_outlier) == 0
#get column names from other dataframe which is not empty
cols <- names(list_data_outlier[[which.max(!inds)]])
#create an empty dataframe with data as 99 and 1 row
empty_df <- data.frame(matrix(99, nrow = 1, ncol = length(cols),
dimnames = list(NULL, cols)))
#replace the dataframes with 0 columns with empty_df
list_data_outlier[inds] <- replicate(sum(inds), empty_df, simplify = FALSE)
R - How can I create an empty dataframe after transposing?
You subset the empty dataframe. If the dataframe with headers is called df
to create 18000 rows with NA
values you can do -
out <- df[1:18000, ]
rownames(out) <- NULL
out
Create an empty data.frame
Just initialize it with empty vectors:
df <- data.frame(Date=as.Date(character()),
File=character(),
User=character(),
stringsAsFactors=FALSE)
Here's an other example with different column types :
df <- data.frame(Doubles=double(),
Ints=integer(),
Factors=factor(),
Logicals=logical(),
Characters=character(),
stringsAsFactors=FALSE)
str(df)
> str(df)
'data.frame': 0 obs. of 5 variables:
$ Doubles : num
$ Ints : int
$ Factors : Factor w/ 0 levels:
$ Logicals : logi
$ Characters: chr
N.B. :
Initializing a data.frame
with an empty column of the wrong type does not prevent further additions of rows having columns of different types.
This method is just a bit safer in the sense that you'll have the correct column types from the beginning, hence if your code relies on some column type checking, it will work even with a data.frame
with zero rows.
Related Topics
Sort Matrix According to First Column in R
Three-Way Color Gradient Fill in R
Rm(List=Ls()) Doesn't Completely Clear the Workspace
Ggplot2: Geom_Text() with Facet_Grid()
Calculating the Difference Between Consecutive Rows by Group Using Dplyr
Connecting Points with Lines in Ggplot2 in R
How to Read CSV Data with Unknown Encoding in R
Plot Circle with a Certain Radius Around Point on a Map in Ggplot2
Ctree() - How to Get the List of Splitting Conditions for Each Terminal Node
How to Give Color to Each Class in Scatter Plot in R
Saving Plot as PDF and Simultaneously Display It in the Window (X11)
Embedding an R HTMLwidget into Existing Webpage
Shiny Saving Url State Subpages and Tabs
How to Write a Function That Calls a Function That Calls Data.Table
Reading Excel File: How to Find the Start Cell in Messy Spreadsheets