aks
aks

Reputation: 1359

R: Insert a vector as a row in data.frame

Can I insert a vector as a row in a data.frame? If so how?

Upvotes: 34

Views: 73304

Answers (3)

exteral
exteral

Reputation: 1061

rbind is good, but really tricky though as to handle the exact row number before and after. A more rapid way is to use insertRow in the package miscTools.

In the dataset example above, the code would be :

my.df <- as.matrix(data.frame(a = runif(10), b = runif(10), c = runif(10)))
my.vec <- c(1, 1, 1)
new.df <- insertRow(my.df,7,my.vec)
new.df

Hope would be helpful.

Upvotes: 6

Eric Leschinski
Eric Leschinski

Reputation: 153882

Make an R dataframe from vector, horizontally

The key insight is to use the R transpose method: t(...) to transpose the vector before you pass it to the data.frame constructor.

my_name_vector      = c("penguin1", "penguin2", "penguin3", "penguin4");
my_data_vector      = c("Skipper",  "Kowalski", "Rico",     "Private");
supplemental_vector = c("Mumble",   "Dorthy",   "Norma",    "Memphis");

#create a data frame out of a transposed vector
penguins = as.data.frame(t(my_data_vector));
#change the names of the dataframe to be the titles
colnames(penguins) <- my_name_vector;

supplemental_data_frame <- data.frame(t(supplemental_vector));
colnames(supplemental_data_frame) <- my_name_vector;
supplemental_data_frame;

#rbind means row bind, pass in two data.frame
penguins <- rbind(penguins, supplemental_data_frame);
penguins;

Prints:

   penguin1 penguin2 penguin3 penguin4
1  Mumble   Dorthy   Norma    Memphis

   penguin1 penguin2 penguin3 penguin4
1  Skipper  Kowalski Rico     Private
2  Mumble   Dorthy   Norma    Memphis

The rbind method is very inefficient, so if you're doing this more than a few hundred rows, expect to wait a long time. If you need to be lightning quick then you need to pre-allocate space or use the list method as shown here: https://stackoverflow.com/a/20689857/445131

Upvotes: 11

Roman Luštrik
Roman Luštrik

Reputation: 70643

I wouldn't claim this to be the most elegant and pretty solution out there, but it gets the job done. Notice that each dataframe row carries its own row name, which becomes a problem when inserting new lines. That being said, you can mend this with row.names (see below).

my.df <- data.frame(a = runif(10), b = runif(10), c = runif(10))
my.vec <- c(1, 1, 1)
new.df <- rbind(my.df[1:5, ], my.vec, my.df[6:nrow(my.df), ])
new.df
            a         b          c
1  0.45433791 0.3798105 0.84514864
2  0.07074529 0.4985765 0.53912585
3  0.09645574 0.5441647 0.96636213
4  0.60788436 0.6070706 0.53791603
5  0.01593911 0.1697248 0.62697924
6  1.00000000 1.0000000 1.00000000
61 0.98455694 0.2206702 0.85500531
7  0.85356834 0.5279596 0.27462326
8  0.48028935 0.6689572 0.05428349
9  0.95675901 0.6875491 0.77642924
10 0.24691330 0.7980741 0.24013096

row.names(new.df) <- 1:nrow(new.df)  # make row names pretty again

Upvotes: 20

Related Questions