【发布时间】:2019-05-06 21:56:46
【问题描述】:
如果我有这样的数据集:
names <- c("Dave", "Ashley", "Drew")
score1 <- c(5, 1, 3)
opponent <- c("Drew", "Dave", "Ashley")
x <- cbind(names, score1, opponent)
x
y <- as.numeric(ifelse(x[, 3]==x[1, 1], x[1, "score1"], ifelse(
x[, 3]==x[2, 1], x[2, "score1"], ifelse(
x[, 3]==x[3, 1], x[3, "score1"], 1))))
y <- (y * score1)
x <- cbind(x, y)
x
我可以创建一个循环来创建一个新列,其中“score1”列中的数字乘以不同行中“y”列中的数字。例如,创建一个新列,其中 [1, 2] 处的值为 5,因为“Dave”在他的行中有“Drew”,所以“Dave”的“score1”列“5”乘以“Drew”' s “score1”栏“3”。有没有办法在一个适用于一百行和一百列的循环中做到这一点?目前,我知道的唯一方法是编写大量像上面这样的“ifelse”语句。
【问题讨论】:
标签: r loops if-statement