Georgia
Georgia

Reputation: 1

Replicating and Altering Data Frame in R

Hi I'm trying replicate a data frame and then alter one of my columns called "i" for iteration based on the replicate number.

E.g. My starting data frame is:

dataframex <- data.frame(i = c(1, 1, 1),
                         x = c(1, 3, 5),
                         y = c(2, 4, 6))
dataframex 
#   i x y
# 1 1 1 2
# 2 1 3 4
# 3 1 5 6

I used the command code

dataframex[rep(1:nrow(dataframex), times=3), ]
#     i x y
# 1   1 1 2
# 2   1 3 4
# 3   1 5 6
# 1.1 1 1 2
# 2.1 1 3 4
# 3.1 1 5 6
# 1.2 1 1 2
# 2.2 1 3 4
# 3.2 1 5 6

But what I really want is:

#     i x y
# 1   1 1 2
# 2   1 3 4
# 3   1 5 6
# 1.1 2 1 2
# 2.1 2 3 4
# 3.1 2 5 6
# 1.2 3 1 2
# 2.2 3 3 4
# 3.2 3 5 6

i.e. the iteration column indicates the number of replicated data sets i have. I want to then use the iteration column to merge this data frame with another.

P.s. sorry this is the first time I've used stackoverflow and I couldn't figure out how to make a table so I hope you can understand my makeshift column separators.

Upvotes: 0

Views: 317

Answers (2)

mnel
mnel

Reputation: 115392

Three possible approaches:

your data

DF <- data.frame(i=1,x=1:3,y=4:6)
# create a list with your data replicated three times
df_list <- replicate(n = 3, DF, simplify = F)
# go along this list and add a replicate column as `i`
df_list <- mapply(function(x,value,i) {x[,i] <- value;x}, value = seq_along(df_list), x = df_list, MoreArgs = list(i='i'), SIMPLIFY = F)
# combine into a data.frame
do.call(rbind,df_list)

even simpler

# don't have `i` defined yet
DF <- data.frame(x=1:3,y=1:4)
# add and combine into a data.frame
do.call(rbind,lapply(1:3, function(i,data) {data$i <- i;data}, data = DF))

Both will result in

##  i x y
## 1 1 1 4
## 2 1 2 5
## 3 1 3 6
## 4 2 1 4
## 5 2 2 5
## 6 2 3 6
## 7 3 1 4
## 8 3 2 5
## 9 3 3 6

using your initial method

new_DF <- DF[rep(1:nrow(DF), times=3), ]
new_DF$i <- rep(1:nrow(DF), times = 3)
new_DF
##     i x y
## 1   1 1 4
## 2   2 2 5
## 3   3 3 6
## 1.1 1 1 4
## 2.1 2 2 5
## 3.1 3 3 6
## 1.2 1 1 4
## 2.2 2 2 5
## 3.2 3 3 6

Upvotes: 1

thelatemail
thelatemail

Reputation: 93813

Set up the data:

test <- read.table(textConnection("i x y
1 1 2
1 3 4
1 5 6"),header=TRUE)

> test
  i x y
1 1 1 2
2 1 3 4
3 1 5 6

lapply from 1:number_of_repeats_wanted to get the result:

result <- do.call(rbind,lapply(1:3,function(i) data.frame(i,test[-1])))

> result
  i x y
1 1 1 2
2 1 3 4
3 1 5 6
4 2 1 2
5 2 3 4
6 2 5 6
7 3 1 2
8 3 3 4
9 3 5 6

Upvotes: 1

Related Questions