Lewistrick
Lewistrick

Reputation: 2879

Extract list of values from column based upon other column

The following code:

df <- data.frame(
  "letter" = c("a", "b", "c", "d", "e", "f"),
  "score" = seq(1,6)
)

Results in the following dataframe:

  letter score
1      a     1
2      b     2
3      c     3
4      d     4
5      e     5
6      f     6

I want to get the scores for a sequence of letters, for example the scores of c("f", "a", "d", "e"). It should result in c(6, 1, 4, 5).

What's more, I want to get the scores for c("c", "o", "f", "f", "e", "e"). Now the o is not in the letter column so it should return NA, resulting in c(3, NA, 6, 6, 5, 5).

What is the best way to achieve this? Can I use dplyr for this?

Upvotes: 1

Views: 73

Answers (2)

see24
see24

Reputation: 1210

If you want to use dplyr I would use a join:

df <- data.frame(
  "letter" = c("a", "b", "c", "d", "e", "f"),
  "score" = seq(1:6)
)

library(dplyr)

df2 <- data.frame(letter = c("c", "o", "f", "f", "e", "e"))

left_join(df2, df, by = "letter")

  letter score
1      c     3
2      o    NA
3      f     6
4      f     6
5      e     5
6      e     5

Upvotes: 0

akrun
akrun

Reputation: 887118

We can use match to create an index and extract the corresponding 'score' If there is no match, then by default it gives NA

df$score[match(v1, df$letter)]
#[1]  3 NA  6  6  5  5

df$score[match(v2, df$letter)]
#[1] 6 1 4 5

data

v1 <- c("c", "o", "f", "f", "e", "e")
v2 <- c("f", "a", "d", "e")

Upvotes: 2

Related Questions