我有一个像这样的数字向量:
S1 S2 S3 S4
.1 .5 .3 .9
其中S1,S2 ......是.1的名称...... 我还有另外一个带有这样的列的df:
sub.id State
S1 CA
S2 OR
S2 OR
S4 CA
S3 CO
我想用基于数据框的等效变量替换第一个向量中的名称。
答案 0 :(得分:3)
尝试
names(v1) <- setNames(df$State, df$sub.id)[names(v1)]
v1
# CA OR CO CA
#0.1 0.5 0.3 0.9
或者
names(v1) <- df$State[match(names(v1), df$sub.id)]
v1 <- structure(c(0.1, 0.5, 0.3, 0.9), .Names = c("S1", "S2", "S3","S4"))
df <- structure(list(sub.id = c("S1", "S2", "S2", "S4", "S3"),
State = c("CA",
"OR", "OR", "CA", "CO")), .Names = c("sub.id", "State"),
class = "data.frame", row.names = c(NA, -5L))