nan
nan

Reputation: 1191

duplicate rows and create new data frame in R

I have a R data frame called intraPByGroup as follows:

group, week1, week2, week3, week4
kiwi,23,43,54,23
eggplant,22,32,33,63
jasmine,23,454,12,654
coconut,32,56,22,31

What I want to do is to create a new data frame which are like the following

user,week1,week2,week3,week4
eggplantA,22,32,33,63
eggplantB,22,32,33,63
eggplantC,22,32,33,63
jasmineA,23,454,12,654
jasmineB,23,454,12,654
jasmineC,23,454,12,654

Basically, the idea is: from the original data set, I select two groups (eggplant and jasmine), and I want to create a new dataframe. This new data frame has "user" variable instead of "group". Each user name is actually "groupname+A(B or C)", and all the rest values are duplicated for all users in the same group.

How should I do that in R?

I am thinking of firstly drop the group names and select a row, and compose one new row, then repeat doing this for each selected group.

eggFrame <- intraPByGroup[intraPByGroup$group=="eggplant",-1]
eggFrame1 <- eggFrame
eggFrame1["user"] <- "Eggplant-A"
eggFrame2 <- eggFrame
eggFrame2["user"] <- "Eggplant-B"
total <- rbind(eggFrame1,eggFrame2)

I think repeatedly doing rbind is stupid, even in this way, is there any other faster ways to do it?

Upvotes: 1

Views: 5492

Answers (1)

dickoa
dickoa

Reputation: 18437

You can do something like this

data <- subset(data, group %in% c("eggplant", "jasmine"))[rep(1:2, each = 3), ]
data$group <- factor(paste0(data$group, LETTERS[1:3]))
data
##          group week1 week2 week3 week4
## 2   eggplantA    22    32    33    63
## 2.1 eggplantB    22    32    33    63
## 2.2 eggplantC    22    32    33    63
## 3    jasmineA    23   454    12   654
## 3.1  jasmineB    23   454    12   654
## 3.2  jasmineC    23   454    12   654

If for any reason you don't like the rownames like this and you want to change "group" to "user"

rownames(data) <- NULL
names(data)[1] <- "user"
data
##        user week1 week2 week3 week4
## 1 eggplantA    22    32    33    63
## 2 eggplantB    22    32    33    63
## 3 eggplantC    22    32    33    63
## 4  jasmineA    23   454    12   654
## 5  jasmineB    23   454    12   654
## 6  jasmineC    23   454    12   654

Upvotes: 5

Related Questions