R将列的值传递为从数组中选择列的值

时间:2011-06-16 14:50:06

标签: r

我试图将现有R属性(列)的值作为标识我想要选择的数组中特定列所需的值。我之前用IF语句编写了一个For循环,但运行速度很慢。

每个人都有一个团体会员资格(1,2或3)。我有他们的团队成员资格概率$ prob1,数据$ prob2和数据$ prob3。

我想传递data $ Group的值,如下所示:

data $ ClstrAffinity = data $ Prob [,data $ Group]

但它不起作用。有任何想法吗?

慢速运行的代码如下。

谢谢。

data$ProbOne = data$Prob[ , 1]
data$ProbTwo = data$Prob[ ,2]
data$ProbThree = data$Prob[ ,3]
data$GroupMembershipNumeric = as.numeric(data$Group)

data[data$Group == 1]

for (a in c(1:nrow(data))) {
  groupMembership = data$GroupMembershipNumeric[a]
  if (groupMembership == 1) {
    data$ClstrAffinity[a] = data$ProbOne[a]
  }
  if (groupMembership == 2) {
    data$ClstrAffinity[a] = data$ProbTwo[a]
  }
  if (groupMembership == 3) {
    data$ClstrAffinity[a] = data$ProbThree[a]
  }
  print(groupMembership)
  groupMembership = NULL
}

2 个答案:

答案 0 :(得分:3)

矩阵索引是您所需要的。我将生成一些示例数据

set.seed(5)
Prob <- matrix(sample(0:10, 15, replace=TRUE)/10, ncol=3)
Group <- sample(1:3,5,replace=TRUE)

然后你想要的结果就是

ProbFinal <- Prob[cbind(1:5,Group)]

答案 1 :(得分:0)

您可以使用which

data$ProbFinal = "NA"

data$ProbOne = data$Prob[ ,1]
data$ProbTwo = data$Prob[ ,2]
data$ProbThree = data$Prob[ ,3]

data$ProbFinal[which(data$Group == 1)] = data$ProbOne[which(data$Group  == 1)]
data$ProbFinal[which(data$Group == 2)] = data$ProbTwo[which(data$Group == 2)]
data$ProbFinal[which(data$Group == 3)] = data$ProbThree[which(data$Group == 3)]