我遇到了循环问题。这个问题应该很容易解决,但是《R for Stata Users》(我使用Stata编程已经有几年了)、Roger Peng的视频和Google似乎都没有帮助到我。你们中的某个人能否向我解释一下我错在哪里?
我正在尝试编写一个循环,通过运行 'thresholds' 数据帧来提取三组列的信息。我可以通过三次编写相同的代码段来实现我想要的功能,但是随着代码变得更加复杂,这将变得非常繁琐。
以下是'thresholds'的示例(由友好的读者添加的
这段代码实现了我想要的功能:
我认为我调用“i”的方式有些问题,但是我不确定该如何正确地做。随着我从Stata切换到R,我的习惯使用本地变量正在困扰着我。
编辑以添加友好读者的
我正在尝试编写一个循环,通过运行 'thresholds' 数据帧来提取三组列的信息。我可以通过三次编写相同的代码段来实现我想要的功能,但是随着代码变得更加复杂,这将变得非常繁琐。
以下是'thresholds'的示例(由友好的读者添加的
dput
输出): threshold_1_name threshold_1_dir threshold_1_value
1 overweight > 25
2 possible malnutrition < 31
3 Q1 > 998
4 Q1 > 998
5 Q1 > 998
6 Q1 > 998
threshold_1_units threshold_2_name threshold_2_dir threshold_2_value threshold_2_units
1 kg/m^2 obese > 30 kg/m^2
2 cm <NA> > NA
3 <NA> Q3 > 998
4 Q3 > 998
5 Q3 > 998
6 Q3 > 998
这段代码实现了我想要的功能:
newvars1 <- paste(thresholds$varname, thresholds$threshold_1_name, sep = "_")
noval <- is.na(thresholds$threshold_1_value)
newvars1 <- newvars1[!noval]
newvars2 <- paste(thresholds$varname, thresholds$threshold_2_name, sep = "_")
noval <- is.na(thresholds$threshold_2_value)
newvars2 <- newvars2[!noval]
newvars3 <- paste(thresholds$varname, thresholds$threshold_3_name, sep = "_")
noval <- is.na(thresholds$threshold_3_value)
newvars3 <- newvars3[!noval]
以下是我尝试循环的方式:
variables <- NULL
for (i in 1:3) {
valuevar <- paste("threshold", i, "value", sep = "_")
namevar <- paste("threshold", i, "name", sep = "_")
newvar <- paste("varnames", i, sep = "")
for (j in 1:length(thresholds$varname)) {
check <- is.na(thresholds[valuevar[j]])
if (check == FALSE) {
newvars <- paste(thresholds$varname, thresholds[namevar], sep = "_")
}
}
variables <- c(variables, newvars)
}
这里是我收到的错误信息:
Error: unexpected '}' in "}"
我认为我调用“i”的方式有些问题,但是我不确定该如何正确地做。随着我从Stata切换到R,我的习惯使用本地变量正在困扰着我。
编辑以添加友好读者的
dput
输出:thresholds <- structure(list(varname = structure(1:6, .Label = c("varA", "varB",
"varC", "varD", "varE", "varF"), class = "factor"), threshold_1_name = c("overweight",
"possible malnutrition", "Q1", "Q1", "Q1", "Q1"), threshold_1_dir = c(">",
"<", ">", ">", ">", ">"), threshold_1_value = c(25L, 31L, 998L,
998L, 998L, 998L), threshold_1_units = c("kg/m^2", "cm", NA,
NA, NA, NA), threshold_2_name = c("obese", "<NA>", "Q3", "Q3",
"Q3", "Q3"), threshold_2_dir = c(">", ">", ">", ">", ">", ">"
), threshold_2_value = c(30L, NA, 998L, 998L, 998L, 998L), threshold_2_units = c("kg/m^2",
"cm", NA, NA, NA, NA)), .Names = c("varname", "threshold_1_name",
"threshold_1_dir", "threshold_1_value", "threshold_1_units",
"threshold_2_name", "threshold_2_dir", "threshold_2_value", "threshold_2_units"
), row.names = c(NA, -6L), class = "data.frame")
for (j in 1:length(thresholds$varname) {
。 - Blue Magisterfor
语句没有闭合括号。 - Blue Magisterdput(head(thresholds))
这样的内容?请参考这里以获得一个好的可重现的示例。 - Blue Magister