Nick Knauer Nick Knauer - 9 days ago 5
R Question

If Column Contains Text in Another Column, Add New Column With Indexed Text

I have two dataframes:

1st Dataframe:

Placement <- c('B-dghealpha', 'B-deAlpha', 'B-edfBeta', 'B-edgesg', 'B-edghe',
'B-polard', 'B-plotter', 'C-wertw', 'OPLTWE', 'optional')

This_Month <- c(2000,4000,4000,5000,5400,9000,1222,1424,2222,1908)

Last_Month <- c(21000, 23400, 26800, 1234, 1245, 4593, 4958, 1223, 1111, 2222)

df1 <- data.frame(Placement, This_Month, Last_Month)

df1

Placement This_Month Last_Month
1 B-dghealpha 2000 21000
2 B-deAlpha 4000 23400
3 B-edfBeta 4000 26800
4 B-edgesg 5000 1234
5 B-edghe 5400 1245
6 B-polard 9000 4593
7 B-plotter 1222 4958
8 C-wertw 1424 1223
9 OPLTWE 2222 1111
10 optional 1908 2222


2nd Dataframe:

Family <- c('ALPHA', 'BETA', 'PLOT', 'OPTION')

df2<-as.data.frame(Family)

df2

Family
1 ALPHA
2 BETA
3 PLOT
4 OPTION


How do I add another column to df1 named:
Family
with the values found in df2 that match with the text contained in the Placement Column of df1?

Final Output Needed:

Placement This_Month Last_Month Family
1 B-dghealpha 2000 21000 ALPHA
2 B-deAlpha 4000 23400 ALPHA
3 B-edfBeta 4000 26800 BETA
4 B-edgesg 5000 1234 NA
5 B-edghe 5400 1245 NA
6 B-polard 9000 4593 NA
7 B-plotter 1222 4958 PLOT
8 C-wertw 1424 1223 NA
9 OPLTWE 2222 1111 NA
10 optional 1908 2222 OPTION


Thanks!

Answer

Does this help you?

df1$Family = NA_character_
p = tolower(Placement)
f = tolower(Family)
sapply(seq_along(f),function(i) df1$Family[grepl(f[i],p)] <<- Family[i])