英文:
Is it possible in base R to replace multiple integers with corresponding strings like a dictionary?
问题
类似于此问题:https://stackoverflow.com/questions/63173687/replace-multiple-values-in-r 但是:我只想使用基本的R,并且我想替换整数,因此下面采用的命名向量解决方案不起作用:
testing <- data.frame(
var1 = c(1, 6, 17)
)
# 这是不可能的
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中是否有更方便的方法?
英文:
Similar to this question: https://stackoverflow.com/questions/63173687/replace-multiple-values-in-r but: I would like to only use base R and I would like to replace integers, so the named vector solution adopted as below does not work:
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]
I know I can do
testing$var1[testing$var1 == 1] <- "ICMP"
testing$var1[testing$var1 == 6] <- "TCP"
testing$var1[testing$var1 == 17] <- "UDP"
but isn't there a more convenient way in base R?
答案1
得分: 2
创建命名向量字典
dict <- c('ICMP', 'TCP', 'UDP')
names(dict) <- c(1, 6, 17)
替换匹配的值
testing$var2 <- dict[as.character(testing$var1)]
var1 var2
1 1 ICMP
2 6 TCP
3 17 UDP
英文:
# 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
答案2
得分: 2
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
英文:
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
答案3
得分: 2
以下是翻译好的部分:
有多种选项。首先,您可以使用字符串作为索引:
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)]
英文:
There is a number of options. First, you can use strings as indices:
dict <- c("1" = "ICMP", "6" = "TCP")
dict[ as.character(testing$var) ]
You can achieve the same by doing names(dict) <- c(1, 6)
.
Then, you can use a reverse hash:
dict <- c(ICMP = 1, TCP = 6)
names(dict)[ match(testing$var1, dict) ]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论