Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R define dimensions of empty data frame

Tags:

r

I am trying to collect some data from multiple subsets of a data set and need to create a data frame to collect the results. My problem is don't know how to create an empty data frame with defined number of columns without actually having data to put into it.

collect1 <- c()  ## i'd like to create empty df w/ 3 columns: `id`, `max1` and `min1`  for(i in 1:10){ collect1$id <- i ss1 <- subset(df1, df1$id == i) collect1$max1 <- max(ss1$value) collect1$min1 <- min(ss1$value) } 

I feel very dumb asking this question (I almost feel like I've asked it on SO before but can't find it) but would greatly appreciate any help.

like image 459
screechOwl Avatar asked Mar 29 '12 00:03

screechOwl


People also ask

How do I initialize an empty data frame in R?

One simple approach to creating an empty DataFrame in the R programming language is by using data. frame() method without any params. This creates an R DataFrame without rows and columns (0 rows and 0 columns).

How do I create an empty data frame size?

Create Empty Dataframe With Size You can create a dataframe with a specified size for both columns and rows. Use the range function to create a sequence of numbers and pass it to the index range or the columns range specify column and row sizes.

How do you define dimensions in R?

dim() in R The dim() is an inbuilt R function that either sets or returns the dimension of the matrix, array, or data frame. The dim() function takes the R object as an argument and returns its dimension, or if you assign the value to the dim() function, then it sets the dimension for that R Object.


2 Answers

Would a dataframe of NAs work? something like:

data.frame(matrix(NA, nrow = 2, ncol = 3))

if you need to be more specific about the data type then may prefer: NA_integer_, NA_real_, NA_complex_, or NA_character_ instead of just NA which is logical

Something else that may be more specific that the NAs is:

data.frame(matrix(vector(mode = 'numeric',length = 6), nrow = 2, ncol = 3))

where the mode can be of any type. See ?vector

like image 51
aatrujillob Avatar answered Sep 19 '22 13:09

aatrujillob


Just create a data frame of empty vectors:

collect1 <- data.frame(id = character(0), max1 = numeric(0), max2 = numeric(0)) 

But if you know how many rows you're going to have in advance, you should just create the data frame with that many rows to start with.

like image 36
Hong Ooi Avatar answered Sep 21 '22 13:09

Hong Ooi