Siddharth Sharma Siddharth Sharma - 1 month ago 5
R Question

Copying Data from a List to another in R

I have the following sample data:


I have stored it in a list in R using the following:

dat = read.csv("File.csv", header = TRUE)

Now I would like to copy this list to another which does not have the "Freq" column but has more rows based on the value of the "Freq" (please refer to reqd. data below)(Freq = 0 has no effect) :


The 3rd row in the original data was doubled in the new data due to its Freq = 2. However, the rows with Freq = 0 still had 1 row in the output data. Any help would be much appreciated.


We can use rep to replicate the sequence of rows of the dataset with the 'Freq' column. As there are 0 values in 'Freq', we need to replace that with 1 and use that vector as argument in rep, expand the rows of 'dat' based on the output of rep as well as select the columns that are not 'Freq' using setdiff.

dat[rep(1:nrow(dat), replace(dat$Freq, dat$Freq==0, 1)), setdiff(names(dat), "Freq")]
#    Class  Sex   Age Survived
#1     1st Male Child       No
#2     2nd Male Child       No
#3     3rd Male Child       No
#3.1   3rd Male Child       No
#4    Crew Male Child       No


dat <- structure(list(Class = c("1st", "2nd", "3rd", "Crew"), Sex = c("Male", 
"Male", "Male", "Male"), Age = c("Child", "Child", "Child", "Child"
), Survived = c("No", "No", "No", "No"), Freq = c(0L, 0L, 2L, 
0L)), .Names = c("Class", "Sex", "Age", "Survived", "Freq"), class =
"data.frame", row.names = c(NA, -4L))