I have two vectors that one (v.num
) corresponds to one variable in df
and the other one (v.type
) is a vector that I want to fill into the df
with the corresponding vector.
v.num<-c(5, 6, 7, 8, 9, 10, 11)
v.type<-c(1, 3, 5, 2, 2, 4, 1)
The df looks like this:
set.seed(2016)
df <- data.frame(v.num=sample(5:11, 40000, replace=TRUE), obs=rnorm(40000))
What I want to do is create a v.type
vector and store the v.type that corresponds to v.num
Like:
head(df)
v.num obs v.type
1 6 1.6149522 3
2 6 -0.2676644 3
3 10 0.3013365 4
4 5 -0.8514377 1
5 8 0.5786278 2
6 5 -1.2974004 1
I tried
for(i in 1:nrow(df)){
for(v in 1:length(v.num){
if(v.num[v]==df$v.num[i]){df$v.type[i]<-v.type[v]}
}}
But it takes pretty long, because I have 40000 rows. What is the most efficient way to do this task?