You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环从向量提取变量名?奇数编号人名无法打印原因

问题解答

能不能用for循环从向量中提取变量名?

可以,对于命名向量,有两种常用的for循环方式提取变量名:要么遍历向量的索引,通过索引关联名字;要么直接遍历向量的名字集合。

你的代码无法正确打印人名的原因

你的for循环遍历的是B_list里的数值(1、2、3),而不是向量的索引或名字。names(i)作用在单个数值上时,会返回NULL,所以paste(names(i), phrase)只会输出短语,没有人名。

修正后的代码

方法一:遍历索引

B_list <- c(Bob=1, Bill=2, Buddy=3)
phrase <- "is a good friend"

for (i in seq_along(B_list)) {
    # 通过索引获取对应的值和名字
    if (B_list[i] %% 2 != 0) {
        print(paste(names(B_list)[i], phrase))
    }
}

方法二:直接遍历名字

B_list <- c(Bob=1, Bill=2, Buddy=3)
phrase <- "is a good friend"

for (name in names(B_list)) {
    # 通过名字获取对应的值
    if (B_list[name] %% 2 != 0) {
        print(paste(name, phrase))
    }
}

两种方法运行后都会输出:

[1] "Bob is a good friend"
[1] "Buddy is a good friend"

内容的提问来源于stack exchange,提问作者R_User_23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:09:21