0

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm! So simple. Thank you so much, @MrFlick

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.