Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:循环列表_R_List_Loops_Paste - Fatal编程技术网

R:循环列表

R:循环列表,r,list,loops,paste,R,List,Loops,Paste,到现在为止,我已经讨论过这个问题好几次了,这次我渴望得到一个有效的解决方案。潜在的问题是我想使用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("da

到现在为止,我已经讨论过这个问题好几次了,这次我渴望得到一个有效的解决方案。潜在的问题是我想使用
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
            }

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

(我知道在这种情况下,我也可以使用
作为.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

dat正如下面的答案所示,不要强制使用特定的方法。找到达成解决方案的最佳方式。
get(paste("dat$",RO,"_I", sep=""))
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
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