为命名向量填写 0

Fill in 0 for named vector

提问人:one 提问时间:6/28/2023 最后编辑:jay.sfone 更新时间:7/12/2023 访问量:71

问:

假设我有以下内容:

all_variable <- c("a","b","d")

all_variable
[1] "a" "b" "d"

myvec <- setNames(c(1),"b")

myvec
b 
1 

有没有一种干净的方法可以获得它:

expected_output <- setNames(c(0,1,0),all_variable)

expected_output 
a b d 
0 1 0 

如果不填写 0,则填写 0。all_variablenames(myvec)

请注意,实际上是从以下内容中提取的:myvectable("b")

table("b"|> factor(levels=all_variable))

a b d 
0 1 0 

因此,我主要对直接操纵 和 的解决方案感兴趣。myvecall_variable

r 字符串 匹配

评论


答:

3赞 jay.sf 6/28/2023 #1

matchall_variable myvec,选项,从all_variable。namesnomatch=0setNames

match(all_variable, names(myvec), nomatch=0) |> setNames(all_variable)
# a b d 
# 0 1 0 
-1赞 jkatam 6/28/2023 #2

如果这有帮助,请您检查一下

all_variable <- c("a","b","d")

# assign values to the vector
expected_output <- c(0,1,0)

# assign the names to the vector
names(expected_output) <- all_variable

# output

a b d 
0 1 0
2赞 G. Grothendieck 6/28/2023 #3

我们假设问题询问结果的分量应包含分量的值,并且所有其他分量应为 0。在问题中包含值 1,但如果它包含 99,那么我们希望作为结果。bbmyvecmyvecsetNames(c(0, 99, 0), c("a", "b", "d"))

在下面的代码中,第一个参数是三个 0 的命名向量。它将第二个参数中指定的名称替换为 。replacemyvec

c(replace(0 * table(all_variable)[all_variable], names(myvec), myvec))
## a b d 
## 0 1 0 

如果结果元素的顺序无关紧要,或者如果已知名称已排序,则我们可以删除 .[all_variable]

c(replace(0 * table(all_variable), names(myvec), myvec))
## a b d 
## 0 1 0 

如果结果是表对象,我们可以删除 c(...)。

如果想要的是结果的分量应该是 1,而不管它的值如何,那么使用bmyvec

c(table(c(all_variable, names(myvec)))[all_variable]) - 1

同样,我们可以省略,并且与以前相同的条件。[all_variable]c(...)

1赞 ThomasIsCoding 6/28/2023 #4

您可以尝试下面的代码

all_variable %>%
    setNames(+(. == "b"), .)

all_variable %>%
    setNames(+(. %in% "b"), .)

这应该给

a b d
0 1 0
1赞 LMc 6/28/2023 #5
x <- setNames(rep(0, length(all_variable)), all_variable)
x[names(myvec)] <- myvec