gpt4 book ai didi

R:遍历列表

转载 作者:行者123 更新时间:2023-12-04 12:30:21 25 4
gpt4 key购买 nike

我已经多次遇到这个问题,这次我渴望得到一个有效的解决方案。潜在的问题是我想用 paste 遍历变量列表。功能。

dat <- read.csv("some file", header=TRUE)  

list.R <- c("IC","IG","DM","IM","IN","EN","RM")

for (RO in list.R){
paste("dat$",RO,"_I", sep="")[
paste("dat$",RO,"_I", sep="") ==
"Strongly disagree"] <- 1
}

我将变量的名称粘贴在一起,但这给了我一个包含块引号的字符串。我已经尝试了以下但到目前为止没有任何效果:
eval(parse(text=paste("dat$",RO,"_I", sep="")))

或者
get(paste("dat$",RO,"_I", sep=""))

你知道如何解决这个问题以便循环工作吗?
我非常感谢您的帮助:)

(我知道在这种情况下我也可以使用 as.numeric(levels(dat$IC_I))[dat$IC_I]但级别的顺序是错误的)

最佳答案

您可以使用简单的赋值运算符来做到这一点——不需要循环(R 中通常是这种情况)。首先,我将构建一个示例数据框,将您的变量存储为字符类型而不是因子:

dat <- data.frame(id=1:2, ID_I=c("Agree", "Strongly Disagree"), IG_I=c("Strongly Disagree", "Agree"), stringsAsFactors=FALSE)
dat
# id ID_I IG_I
# 1 1 Agree Strongly Disagree
# 2 2 Strongly Disagree Agree

现在您可以使用列索引将“强烈不同意”替换为 1:
cols <- c("ID_I", "IG_I")
dat[,cols][dat[,cols] == "Strongly Disagree"] <- 1
dat
# id ID_I IG_I
# 1 1 Agree 1
# 2 2 1 Agree

关于R:遍历列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com