0

I have a dataframe df.

V1  V2 V3
A   1  3
A   2  8
B   4  12
C   3  2
R   8  9

I also have a list lst that works as a map, I can pass a string as an index to the list and it will return a string value. E.g.

lst[["A"]] => "AB"
lst[["B"]] => "BA"
lst[["C"]] => "FE"
lst[["R"]] => "WE"

What I want is to create a new column for df in relation to an existing column. The first column in df will work as the key index to the list and it will return in the same row in the new column the respective value.

I would like to end up with:

V1 V2 V3  V4
A  1  3   AB
A  2  8   AB
B  4  12  BA
C  3  2   FE
R  8  9   WE

Also I want to avoid for-loops since my actual data is very large and also because I would like to see a different and elegant solution. Is there a way to do the above?

Thank you in advance.

user159941
  • 331
  • 5
  • 15
  • 1
    When you create examples (especially in the `r` tag) please always create your data in a reproducible, runnable way. That means we should be able to copy, paste and run the code to create your example data and see the example code. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Hack-R Sep 14 '17 at 14:38

2 Answers2

2
dat = read.table("clipboard", header = TRUE)

lst = list("AB", "BA", "FE", "WE")
names(lst) = c("A", "B", "C", "R")

dat$V4 = lst[dat$V1]

> dat
  V1 V2 V3 V4
1  A  1  3 AB
2  A  2  8 AB
3  B  4 12 BA
4  C  3  2 FE
5  R  8  9 WE
Kristofersen
  • 2,736
  • 1
  • 15
  • 31
  • This is what I was looking for. I was using instead double brackets: dat$V4 <- lst[[dat$V1]]. Could you please explain the difference and why it works with single brackets? Thank you – user159941 Sep 14 '17 at 14:48
  • @user159941 glad it works. There is a pretty detailed response on that at https://stackoverflow.com/questions/1169456/the-difference-between-and-notations-for-accessing-the-elements-of-a-lis – Kristofersen Sep 14 '17 at 14:51
0

Using dplyr:

df%>%mutate(V4=lst[V1])

#  V1 V2 V3 V4
#1  A  1  3 AB
#2  A  2  8 AB
#3  B  4 12 BA
#4  C  3  2 FE
#5  R  8  9 WE
tushaR
  • 3,083
  • 1
  • 20
  • 33