amitjo
amitjo

Reputation: 61

Appending and printing rows in a frame in R

I'm trying to crate a data frame in R by generating rows and appending them one by one. I am doing following

# create an empty data frame.

x <- data.frame ()

# Create 2 lists.

 l1 <- list (a = 9, b = 2, c = 4)
 l2 <- list (a = 7, b = 2, c = 3)

# Append and print.

x <- rbind (x, l1)
x

  a b c
2 9 2 4

# append l2

x <- rbind (x, l2)
x

   a b c 
2  9 2 4
21 7 2 3

# Append again

 x <- rbind (x, l2)
 x

   a b c
2  9 2 4  
21 7 2 3  
3  7 2 3

# Append again.

x <- rbind (x, l2)
x

   a b c   
2  9 2 4 
21 7 2 3  
3  7 2 3  
4  7 2 3

My question is when I print x, what is the significance of the values printed at the beginning of each row ( ie the values 2, 21, 3, 4...) and why these values are appearing as they are, I'd expect then to have been 1,2, 3, 4 .... and so on for shown the indexes of corresponding rows.

Please help.

Upvotes: 2

Views: 95

Answers (2)

Nikos
Nikos

Reputation: 3297

I think your issue is that you are trying to rbind a data.frame with a list. If you change your rbind commands to this:

x <- rbind (x, as.data.frame(l1))

you won't have an issue.

If you have many lists, may I suggest the data.table package which is very convenient and fast. An example follows:

library(data.table)
n = 100;
V=vector("list",n)
for (i in 1:n) {
  V[[i]]<-list(a=runif(1),b=runif(1),c=runif(1));
}
V=rbindlist(V)
V

Thanks.

Upvotes: 2

Michele Usuelli
Michele Usuelli

Reputation: 2000

You won't have strange row names if you avoid initializing an empty data frame.

x <- as.data.frame(l1)
x <- rbind (x, l1)
x <- rbind (x, l2)
x <- rbind (x, l2)
x

If you want to bind rows in a more efficient way, I recommend you the function rbindlist from the data.table package.

Upvotes: 1

Related Questions