I have a data frame:
df = read.table(text="index group S1 S2 S3 S4
1 A 2 3 4 6
2 A 3 4 1 6
3 A 2 4 1 5
4 B 5 6 2 3
5 B 6 4 9 10
6 B 5 4 8 11
7 B 11 12 8 10
8 C 11 9 10 12
9 C 10 8 11 12
10 C 9 8 11 12
11 D 8 9 10 12
12 D 9 10 8 11", header=T, stringsAsFactors=F)
I would like to replace values of column S1-S4 with values of column 'group', if the value in column S1-S4 match the column "index". so the expected result is :
index S1 S2 S3 S4
1 A A B B
2 A B A B
3 A B A B
4 B B A A
5 B B C C
6 B B C D
7 D D C C
8 D C C D
9 C C D D
10 C C D D
11 C C C D
12 C C C D
I can get the result with a loop and match but I am not satisfied the solution. I appreciate any helps
df[, 3:6] <- df$group[unlist(df[, 3:6])]? It's as simple as subsetting the group column by the (unlisted) indices in columns S1-S4.