John Snow
John Snow

Reputation: 153

Replacing column values in R

Example df:

index    name    V1    V2   etc
1        x       2     1
2        y       1     2
3        z       3     4
4        w       4     3

I would like to replace values in columns V1 and V2 with related values in name column for particular index value. Output should look like this:

index    name    V1    V2   etc 
1        x       y     x    
2        y       x     y    
3        z       z     w  
4        w       w     z   

I have tried multiple merge statements in loop but not sure how I can replace the values instead of creating new columns and also got a duplicate name error.

V<-2 # number of V columns
names<-c()
for (i in 1:k){names[[i]]<-paste0('V',i)}
lookup_table<-df[,c('index','name'),drop=FALSE] # it's at unique index level

for(col in names){ 
df<- merge(df,lookup_table,by.x=col,by.y="index",all.x = TRUE)
}

Upvotes: 1

Views: 99

Answers (1)

akrun
akrun

Reputation: 887891

We can do

df[3:4] <- lapply(df[3:4], function(x) df$name[x])

Or without looping

df[3:4] <- df$name[as.matrix(df[3:4])]
df
#  index name V1 V2
#1     1    x  y  x
#2     2    y  x  y
#3     3    z  z  w
#4     4    w  w  z

data

df <- structure(list(index = 1:4, name = c("x", "y", "z", "w"), V1 = c(2L, 
1L, 3L, 4L), V2 = c(1L, 2L, 4L, 3L)), .Names = c("index", "name", 
"V1", "V2"), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 4

Related Questions