Mike Liu
Mike Liu

Reputation: 3

Replicate rows with different values in one column

Can anyone help on replicate rows in R:

I have a dataset like -

ID Study X Y Z Time
1  2     3 4 5 0
2  2     3 4 5 0
3  2     3 4 5 0

Also have a vector of time c(1,1.3,4,5,8,24,34,55,66)

I would like to replicate each row with new rows at column Time with values list above, such as:

ID Study X Y Z Time
1  2     3 4 5 0
1  2     3 4 5 1
1  2     3 4 5 1.3
1  2     3 4 5 4

Upvotes: 0

Views: 215

Answers (2)

PKumar
PKumar

Reputation: 11128

One way to do it like this:

Data:

dt <- read.table(text=c("ID Study X Y Z Time",
  "1  2     3 4 5 0",
  "2  2     3 4 5 0",
  "3  2     3 4 5 0"), header=T)

Solution:

vect <- list(c(0,1,1.3,4,5,8,24,34,55,66)) #convert the vector to a list
dt$Time <- vect #use that converted list to add as column, it will replace the existing Time column
dt <- tidyr::unnest(dt, Time) #use tidyr::unnest to unnest the column time

OR as suggested by @thelatemail, you can use baseR like so(using the default vectorization in Base R):

newdt <- dt[rep(seq_len(nrow(dt)), each=length(vect)),]
newdt$Time <- vect #We can see the vectorization of values in R here

I have two assumptions here, The existing Time variable is completely zero, and you want a zero value of time for each of the IDs on top.

Output:

   #   ID Study X Y Z Time
   # 1   1     2 3 4 5  0.0
   # 2   1     2 3 4 5  1.0
   # 3   1     2 3 4 5  1.3
   # 4   1     2 3 4 5  4.0
   # 5   1     2 3 4 5  5.0

Upvotes: 1

ozanstats
ozanstats

Reputation: 2856

If I understand your question correctly, you want to modify time values starting from the second observation using the given vector. You can simply use the following expression, just be careful about lengths to prevent unintended recycling:

df$Time[-1] <- time_vec # alternatively: df$Time[2:n] <- time_vec where n = 10 in this case

Data:

df <- data.frame(
  ID = 1:10,
  Study = rep(2, 10),
  X = rep(3, 10),
  Y = rep(4, 10),
  Z = rep(5, 10),
  Time = rep(0, 10)
)

time_vec <- c(1, 1.3, 4, 5, 8, 24, 34, 55, 66)

Upvotes: 0

Related Questions