简体   繁体   English

替换R中的列值

[英]Replacing column values in R

Example df: 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. 我想用名称列中的相关值替换特定索引值的V1和V2列中的值。 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. 我在循环中尝试了多个merge语句,但不确定如何替换值而不是创建新列,并且还出现重复的名称错误。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM