Hello everyone: I have a question related to the previous message about the rounding program (available here: R: combine the contents inside each line so that the total amount is equal to the number that I specify ).
The program is designed to round the contents within each line, so the total amount of lines is equal to the number that I specify. Copied from the original post, here is the MWE that works:
Round <- function(x, target) {
r.x <- round(x)
diff.x <- round(x) - x
if ((s <- sum(r.x)) == target) {
return(r.x)
} else if (s > target) {
select <- seq(along=x)[diff.x > 0]
which <- which.max(diff.x[select])
x[select[which]] <- r.x[select[which]] - 1
Round(x, target)
} else {
select <- seq(along=x)[diff.x < 0]
which <- which.min(diff.x[select])
x[select[which]] <- r.x[select[which]] + 1
Round(x, target)
}
}
dat <- read.table(header = TRUE, row.names = paste0('place', 1:4),
text="race1 race2 total
1.2 2.1 3.4
3.4 3.6 7.0
7.7 0.8 8.5
5.3 1.4 6.7")
totals <- c(4.0, 7.0, 8.0, 7.0)
do.call(rbind, lapply(1:nrow(dat), function(x) Round(dat[x, -3], totals[x])))
: , , , , 1 . , 2 3 4. , , 6-8 2, . 6 8, .
, "Round" , :
dat <- read.table(header = TRUE, row.names = paste0('place', 1:4),
text="race1 race2 total
1.2 2.1 3.4
3.4 3.6 7.0
7.7 0.8 8.5
5.3 1.4 6.7")
totals <- c(4.0, 5.0, 8.0, 7.0)
do.call(rbind, lapply(1:nrow(dat), function(x) Round(dat[x, -3], totals[x])))
Error in data.frame(value, row.names=rn, check.names = FALSE, check.rows
= FALSE) : 'row.names' should specify one of the variables
( c (4.0, 7.0,...) c (4.0, 5.0,...))
, , , , , , , 4 . ( data.frame , 14 .)
, rawr, , , 3 .
:
Round <- function(x, target){
r.x <- round(x)
diff.x <- round(x) - x
if ((s <- sum(r.x)) == target) {return(r.x)
} else if (s > target) {
select <- seq(along=x)[diff.x != 0]
which <- which.max(diff.x[select])
x[select[which]] <- r.x[select[which]] - 1
Round(x, target)
}
else{
select <- seq(along=x)[diff.x != 0]
which <- which.min(diff.x[select])
x[select[which]] <- r.x[select[which]] + 1
Round(x, target)
}
}
, :
dat <- read.table(header = TRUE, row.names = paste0('district', 1:4),
text="race1 race2 total
1.2 2.1 3.4
3.4 3.6 7.0
7.7 0.8 8.5
5.3 1.4 6.7")
totals <- c(4.0, 5.0, 12.0, 7.0)
do.call(rbind, lapply(1:nrow(dat), function(x) Round(dat[x, -3], totals[x])))
Error in data.frame(value, row.names = rn, check.names = FALSE, check.rows = FALSE) :
'row.names' should specify one of the variables