list R:遍历列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25109055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:04:59  来源:igfitidea点击:

R: loop through list

rlistloopspaste

提问by teeglaze

I've come over this problem a few times by now, and this time I am eager to get an efficient solution. The underlying problem is that I want to loop through a list of variables with the pastefunction.

我已经多次遇到这个问题,这次我渴望得到一个有效的解决方案。潜在的问题是我想用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
            }

I pasted the name of the variable together, but this gives me a string in block quotes. I've tried the following but nothing worked so far:

我将变量的名称粘贴在一起,但这给了我一个包含块引号的字符串。我已经尝试了以下但到目前为止没有任何效果:

eval(parse(text=paste("dat$",RO,"_I", sep="")))

or

或者

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

do you know how to solve this so that the loop works? I would very much appreciate your help :)

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

(I know in this case I could also use as.numeric(levels(dat$IC_I))[dat$IC_I]but the order of the levels is wrong)

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

回答by josliber

You can do this with simple assignment operators -- there's no need for a loop (as is usually the case in R). First, I'll construct a sample data frame, with your variables stored as the character type instead of as factors:

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

Now you can use column indexing to replace "Strongly Disagree" with 1:

现在您可以使用列索引将“强烈不同意”替换为 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