对于R中带字符串变量的循环

时间:2017-05-05 13:20:50

标签: r

data = data.frame(
focal = c("John","John","John","John","Albert","Charles","Charles","Jay","Jay","Jay"),
type = c("Baseline","Baseline","Baseline","Baseline","Experimental","Experimental","Experimental","Baseline","Baseline","Baseline"),
partner5M = c("Martin","Albert","Chris","Chris","John","Albert","Rich","Martin","Albert","Alfred"),
duration = sample(c(1:50),10),
header = TRUE
)

我需要从我的数据框中提取数据,如下所示(它有效):

Xindiv = database[ which ( data$focal == "John" & data$type == "Baseline" & database$partner5M == "indiv"),4]
Xindiv = unlist(Xindiv,use.names = FALSE)
Xindiv = chron(times = Xindiv)

问题在于我需要为很多人做到这一点,而且我还需要能够快速更改的条件。

所以我想做的是一个for循环,大致如下:

indiv = c("indiv1","indiv2","indiv3") #every different individuals in partner5M
for(indiv in length(indiv)) {

Xindiv = database[ which ( database$Focal == "JohnDoe" & database$Type == "Baseline" & database$Partner5m == "indiv"),24]
Xindiv = unlist(Xindiv,use.names = FALSE)
Xindiv = chron(times = Xindiv)
}

我希望结果如下:

Xindiv1 = ...
Xindiv2 = ...
Xindiv3 = ...

等等,但我不知道如何制作这样的循环,所以我非常感谢有关该方法的任何建议。

干杯, 最大

0 个答案:

没有答案