类似于这个问题:替换r中的多个值,但是:我想只使用基数r并且我想替换整数,所以下面采用的命名向量解决方案不起作用:
testing <- data.frame(
var1 = c(1, 6, 17)
)
# this is not possible
dict <- c(
1 = 'ICMP',
6 = 'TCP',
17 = 'UDP',
)
testing$var1 <- dict[testing$var1]
我知道我能做到
testing$var1[testing$var1 == 1] <- "ICMP"
testing$var1[testing$var1 == 6] <- "TCP"
testing$var1[testing$var1 == 17] <- "UDP"
但是以R为底没有更方便的方法吗?
# create named vector dict
dict <- c('ICMP', 'TCP', 'UDP')
names(dict) <- c(1,6,17)
# replace matching values
testing$var2 <- dict[as.character(testing$var1)]
# var1 var2
# 1 1 ICMP
# 2 6 TCP
# 3 17 UDP
testing <- data.frame(
var1 = c(1, 6, 17)
)
dict <- data.frame(code = c(1, 6, 17), abbr = c('ICMP', 'TCP', 'UDP'))
merge(testing, dict, by.x = "var1", by.y = "code")
# var1 abbr
#1 1 ICMP
#2 6 TCP
#3 17 UDP
testing$var1 <- merge(testing, dict, by.x = "var1", by.y = "code")$abbr
有很多选项。首先,您可以使用字符串作为索引:
dict <- c("1" = "ICMP", "6" = "TCP")
dict[ as.character(testing$var) ]
您可以通过执行names(dict) <- c(1, 6)
来实现相同的目标。
然后,你可以使用反向哈希:
dict <- c(ICMP = 1, TCP = 6)
names(dict)[ match(testing$var1, dict) ]