0

I have a column in a data set A: 1, 1 , 2 , 2, 3, 4, 4, 4, 4, 5, 5. and a data set B B:1, 2, 3, 4, 5

Is there a way how to respectively assign the values of B to the values of A.

The desirable result has to be :

A   B   C
1   v   v
1   b   v
2   n   b
2   m   b
3   k   n
4       m
4       m
4       m
4       m
5       k
5       k
2
  • yeah you are right i will edit that Commented Sep 1, 2015 at 13:44
  • Depends on many assumptions, but this works df$C = (df$B)[df$A]
    – Vlo
    Commented Sep 1, 2015 at 13:50

1 Answer 1

2

You could try

C <- B[A]
#> C
# [1] "v" "v" "b" "b" "n" "m" "m" "m" "m" "k" "k"

If you want to store this result in a data frame, you could use

length(B) <- length(A) # adapt the length of column B to that of column A
df <- cbind(A, B, C) # generate a matrix with three columns
df[is.na(df)] <- "" # remove the NA entries in column B (replace them with     
                    # an empty string) in the rows where it is not defined
df <- as.data.frame(df) # convert the matrix into a data frame
#> df
#   A B C
#1  1 v v
#2  1 b v
#3  2 n b
#4  2 m b
#5  3 k n
#6  4   m
#7  4   m
#8  4   m
#9  4   m
#10 5   k
#11 5   k

data

A <- c(1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5)
B <- c("v", "b", "n", "m", "k")

However, if you already have the columns A and B stored in a data frame and you only need to generate column C, you could obtain this result using df$C <- with(df, B[A])

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.