在R基中是否可以像字典一样用对应的字符串替换多个整数?[duplicate]

vc6uscn9  于 2023-01-10  发布在  其他
关注(0)|答案(3)|浏览(149)
    • 此问题在此处已有答案**:

R replace value in a column by a dictionary table without using merge or join(1个答案)
Replace values from another dataframe by IDs(4个答案)
20小时前关门了。
与此问题类似:Replace multiple values in 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进制中不是有更方便的方法吗

mmvthczy

mmvthczy1#

# 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
tp5buhyn

tp5buhyn2#

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
xdyibdwo

xdyibdwo3#

有很多选择。首先,你可以使用字符串作为索引:

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

相关问题