簡體   English   中英

替換R中的列值

[英]Replacing column values in 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   

我在循環中嘗試了多個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)
}

我們可以做的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM