Creating new variable based on index position and

2019-09-01 03:34发布

I could use some help. I need to add a new variable to a dataframe based on whether or not the value of a variable in a dataframe equals the index value of another vector. Below is a simplified example:

vector [2 7 15 4 5]

dataframe (4 variables; Index, Site, Quad, Count)

Index Site Quad Count
1     2    3    0
1     3    7    2
2     1    8    0
2     3    3    1
3     2    3    0
4     3    7    2
5     1    8    0
5     3    3    1

The variable I would like to create would match value of df$Index from the dataframe with the matching position in the vector. That is, when df$Index = 1, the new variable would be 2 (position 1 in the vector), when df$Index = 2, the new variable would be 7 (position 2 in the vector), when df$Index = 3, the new variable would be 3 (position 3 in the vector).

I've ended up in a R wormhole, and know the solution is simple, but I cannot seem to get it. Thanks for any help.

标签: r
1条回答
老娘就宠你
2楼-- · 2019-09-01 03:55

If your indexes are atually integer indices, for example

dd<-read.table(text="Index Site Quad Count
1     2    3    0
1     3    7    2
2     1    8    0
2     3    3    1
3     2    3    0
4     3    7    2
5     1    8    0
5     3    3    1", header=TRUE)
vec <- c(2, 7, 15, 4, 5)

Then you can create the new column with

dd$value <- vec[dd$Index]
dd
#   Index Site Quad Count value
# 1     1    2    3     0     2
# 2     1    3    7     2     2
# 3     2    1    8     0     7
# 4     2    3    3     1     7
# 5     3    2    3     0    15
# 6     4    3    7     2     4
# 7     5    1    8     0     5
# 8     5    3    3     1     5
查看更多
登录 后发表回答