有两列。 在新列中,我希望随机添加或减去其他两列:
for (i in 1:nrow(data) {
if (round(runif(1, 1,2),0) == 1) {
data$p_p2= data$p[i] + data$p2[i]
} else {
data$p_p2 = data$p[i] - data$p2[i]
}
}
如,
p p1 p_p2 *goal*
1 3 -2
3 3 6
5 2 7
由于
答案 0 :(得分:2)
尝试使用ifelse
data$p_p2 <- with(data, ifelse(round(runif(nrow(data),1,2),0)==1,
p+p1, p-p1))
或修改您的代码
data$p_p2 <- NA
for (i in 1:nrow(data)) {
if (round(runif(1, 1,2),0) == 1) {
data$p_p2[i]= data$p[i] + data$p1[i] }
else {
data$p_p2[i] = data$p[i] - data$p1[i]
}
}
data <- structure(list(p = c(1, 3, 5), p1 = c(3, 3, 2), p_p2 = c(NA,
NA, NA)), .Names = c("p", "p1", "p_p2"), row.names = c(NA, -3L
), class = "data.frame")
答案 1 :(得分:1)
对于此类问题,不需要for循环。将逻辑视为“新变量”是一种很好的做法,因为它往往使事情更容易使用。
set.seed(42) # for reproducibility
dat <- as.data.frame( # dat because data is a command, don't overwrite it
matrix(round(runif(100,1,10), nrow = 50, ncol = 2)) # example data
)
# Random response to question: Should be added? TRUE/FALSE
dat$Test <- sample(c(TRUE,FALSE),50,replace = TRUE)
# IF TRUE, ADD, ELSE, SUBTRACT
dat$Result <- ifelse(dat$Test, dat$V1 + dat$V2, dat$V1 - dat$V2)