bvowe
bvowe

Reputation: 3384

Random Number Sequence And Constant

Sample Data

set.seed(1)
data=data.frame("id"=c(sort(rep(1:100,3))),
                "survey"=c(rep(1:3,100)))
data$age = ifelse(data$survey == 1, sample(30:60,100,replace=T),0)

Goal is to get a random number AGE for every row where survey equals to 1. Then I want to add the value of 3 to each AGE as a sequence. So eg if AGE at survey equals to 1 is 20 then AGE at survey 2 equals to 23 and AGE at survey 3 equals to 26. I show sample small data below

datasmall = data=data.frame("id"=c(sort(rep(1:4,3))),
                            "survey"=c(rep(1:3,4)),
                            "age"=c(50,53,56,52,55,58,44,47,50,39,42,45))

Upvotes: 0

Views: 52

Answers (1)

jay.sf
jay.sf

Reputation: 72623

You could simply add three by respective subsetting.

set.seed(1)
data$age <- NA  # if column does not yet exist
data$age[data$survey == 1] <- sample(30:60, length(data$age[data$survey == 1]), 
                                     replace=TRUE)
data$age[data$survey == 2] <- data$age[data$survey == 1] + 3
data$age[data$survey == 3] <- data$age[data$survey == 2] + 3

head(data)
#   id survey age
# 1  1      1  38
# 2  1      2  41
# 3  1      3  44
# 4  2      1  41
# 5  2      2  44
# 6  2      3  47

Upvotes: 1

Related Questions