Daniel
Daniel

Reputation: 7832

Insert "empty" rows (filling up) in data frame in R

Problem solved, solution added at bottom of posting!

I'd like to know how to "fill" a data frame by inserting rows in between existing rows (not appending to the end).

My situation is following:

Problem:

1) I need an X-axis ranging from 0 to 100

2) Not all possible percentage values in var were chosen, for instance I have 30 times the answer "20%", but no answer "19%". For the x-Axis this means, the y-Value at x-position 19 is "0", the y-value at x-position 20 is "30".

To prepare my data (this one variable) for plotting it with ggplot, I transformend it via the table function:

dummy <- as.data.frame(table(var))

Now I have a column "Var1" with the answer categories and a column "Freq" with the counts of each answer categorie.

In total, I have 57 rows, which means that 44 possible answers (values from 0 to 100 percent) were not stated.

Example (of my dataframe), "Var1" contains the given answers, "Freq" the counts:

     Var1 Freq
1     0    1
2     1   16
3     2   32
4     3   44
5     4   14
...
15   14    1
16   15  169 # <-- See next row and look at "Var1"
17   17    2 # <-- "16%" was never given as answer

Now my question is: How can I create a new data frame which inserts a row after row 16 (with "Var1"=15) where I can set "Var1" to 16 and "Freq" to 0?

     Var1 Freq
...
15   14    1
16   15  169
17   16    0 # <-- This line I like to insert
18   17    2

I've already tried something like this:

dummy_x <- NULL
dummy_y <- NULL

for (k in 0:100) {
  pos <- which(dummy$Var1==k)
  if (!is.null(pos)) {
    dummy_x <- rbind(dummy_x, c(k))
    dummy_y <- rbind(dummy_y, dummy$Freq[pos])
  }
  else {
    dummy_x <- rbind(dummy_x, c(k))
    dummy_y <- rbind(dummy_y, 0)
  }
}

newdataframe <- data.frame(cbind(dummy_x), cbind(dummy_y))

which results in the error that dummy_x has 101 values (from 0 to 101, correct), but dummy_y only contains 56 rows?

The result should be plotted like this:

plot(ggplot(newdataframe, aes(x=Var1, y=Freq)) +
   geom_area(fill=barcolors, alpha=0.3) +
   geom_line() +
   labs(title=fragetitel, x=NULL, y=NULL))

Thanks in advance, Daniel

Solution for this problem

plotFreq <- function(var, ftitle=NULL, fcolor="blue") {
# create data frame from frequency table of var
# to get answer categorie and counts in separate columns
dummyf <- as.data.frame(table(var))
# rename to "x-axis" and "y-axis"
names(dummyf) <- c("xa", "ya")
# transform $xa from factor to numeric
dummyf$xa <- as.numeric(as.character(dummyf$xa))
# get maximum x-value for graph
maxval <- max(dummyf$xa)
# Create a vector of zeros 
frq <- rep(0,maxval)
# Replace the values in freq for those indices which equal dummyf$xa
# by dummyf$ya so that remaining indices are ones which you 
# intended to insert 
frq[dummyf$xa] <- dummyf$ya
# create new data frame
newdf <- as.data.frame(cbind(var = 1:maxval, frq))
# print plot
ggplot(newdf, aes(x=var, y=frq)) +
  # fill area
  geom_area(fill=fcolor, alpha=0.3) +
  # outline
  geom_line() +
  # no additional labels on x- and y-axis
  labs(title=ftitle, x=NULL, y=NULL)
}

Upvotes: 1

Views: 23209

Answers (3)

imriss
imriss

Reputation: 1971

This is the Aditya's code plus some conditions to handle special cases:

insertRowToDF<-function(X,index_after,vector_to_insert){
  stopifnot(length(vector_to_insert) == ncol(X)); # to check valid row to be inserted
  if (index_after != 0) {
  if (dim(X)[1] != index_after) {
  X <- rbind(X[1:index_after,], vector_to_insert, X[(index_after+1):nrow(X),]);
  } else {
  X <- rbind(X[1:index_after,], vector_to_insert);
  }
  } else {
  if (dim(X)[1] != index_after) {
  X <- rbind(vector_to_insert, X[(1):nrow(X),]);
  } else { 
  X <- rbind(vector_to_insert);
  }
  }
  row.names(X)<-1:nrow(X);
  return (X);
 }     

Upvotes: 2

CHP
CHP

Reputation: 17189

I think this is much simpler solution. Looping is not necessary. Idea is to create a vector of size of desired result, with all values set to zero and then replace appropriate value with non zero values from frequency table.

> #Let's create sample data
> set.seed(12345)
> var <- sample(100, replace=TRUE)
> 
> 
> #Lets create frequency table
> x <- as.data.frame(table(var))
> x$var <- as.numeric(as.character(x$var))
> head(x)
  var Freq
1   1    3
2   2    1
3   4    1
4   5    2
5   6    1
6   7    2
> #Create a vector of 0s 
> freq <- rep(0, 100)
> #Replace the values in freq for those indices which equal x$var  by x$Freq so that remaining 
> #indices are ones which you intended to insert 
> freq[x$var] <- x$Freq
> head(freq)
[1] 3 1 0 1 2 1
> #cbind data together 
> freqdf <- as.data.frame(cbind(var = 1:100, freq))
> head(freqdf)
  var freq
1   1    3
2   2    1
3   3    0
4   4    1
5   5    2
6   6    1

Upvotes: 3

Aditya Sihag
Aditya Sihag

Reputation: 5167

try something like this

 insertRowToDF<-function(X,index_after,vector_to_insert){
      stopifnot(length(vector_to_insert) == ncol(X)); # to check valid row to be inserted
      X<-rbind(X[1:index_after,],vector_to_insert,X[(index_after+1):nrow(X),]);
      row.names(X)<-1:nrow(X);
      return (X);
 }

you can call it with

df<-insertRowToDF(df,16,c(16,0)); # inserting the values (16,0) after the 16th row

Upvotes: 3

Related Questions