我正面临着R中for循环的问题。如果某个条件适用于数据元素,则需要创建一个新向量。但是,我只希望R遍历数据集的前49列。这是迄今为止的代码,但R返回多个错误消息。使用带if条件的for循环创建新向量
meanedu = c()
count= 0
sum = 0
###HV105.01:HV105.49 are the columns for which I want the for loop to run###
for i in ncol(HV105.01:HV105.49) i++) }
###burkina cut is the name of the dataset. I want the for loop to run for all rows###
for (j in nrow(burkinacut) j++) {
##defining a new variable age which is the position [1,1] in my dataset###
age = burkinacut[i,j]
if (age >= 25) {
##if age>=25 create a new vector adult edu which is the value 49 spaces to the right from the current data element##
adultedu= (i, j+49)
sum = sum + adultedu ###sum this vector###
count= count++
}
}
}
我将不胜感激关于如何使代码运行的任何建议。我试图解释说明我希望做什么。从我所做的研究来看,apply,lapply或mapply函数可能是最好用的,但我不明白在这种情况下如何使用它们。
首先,您for'循环的语法关闭。尝试类似'for(我在1:49){做点什么}' – keegan
R是一种解释型语言,它可以运行一小段代码来查看语法是否有效。例如,在这里你可以运行'HV105.01:HV105.49',这个错误会告诉你这不是一个有效的方法来获得一系列的列。您可以通过尝试使用'HV105.01'来测试期间是否适用于访问列,当这种情况不起作用时,您可能会记得使用'['代替。同样,'2 ++'不起作用,所以'i ++'也不起作用。 – Gregor