替换R中的列值

时间:2017-06-06 12:58:10

标签: r

示例df:

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

我想将列V1和V2中的值替换为特定索引值的名称列中的相关值。输出应如下所示:

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

我在循环中尝试了多个合并语句,但不确定如何替换值而不是创建新列,并且还出现重复的名称错误。

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)
}

1 个答案:

答案 0 :(得分:4)

我们可以做到

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

或没有循环

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

数据

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))
相关问题