【问题标题】:R: loop through listR:遍历列表
【发布时间】:2014-09-26 08:36:28
【问题描述】:

到目前为止,我已经多次遇到过这个问题,这次我渴望得到一个有效的解决方案。根本问题是我想使用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 list loops paste


【解决方案1】:

您可以使用简单的赋值运算符来做到这一点——不需要循环(在 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

【讨论】:

    猜你喜欢
    • 2016-09-19
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多