编辑:我已做出更改,但我仍然收到错误
data <- readLines(con = stdin(), n = 3)[[2]]
weights <- readLines(con = stdin(), n = 3)[[3]]
cat(weighted.mean(as.numeric(data), as.numeric(weights)))
新输出:
Error in as.numeric(weights) :
cannot coerce type 'closure' to vector of type 'double'
Calls: cat -> weighted.mean -> weighted.mean.default
In addition: Warning message:
In weighted.mean(as.numeric(data), as.numeric(weights), na.rm = TRUE) :
NAs introduced by coercion
Execution halted
在使用as.numeric之后,我不明白参数如何仍然不是数字。我试图在两个数组中读取并找到加权平均值。输出1,2,3和4,5,6只是我输入的示例输入。
data <- readLines(con = stdin(), n = 3)[[2]]
as.numeric(data)
weights <- readLines(con = stdin(), n = 3)[[3]]
as.numeric(weights)
cat(weighted.mean(data, weights))
这是我的输出:
> data <- readLines(con = stdin(), n = 3)[[2]]
1
2
3
> as.numeric(data)
[1] 2
> weights <- readLines(con = stdin(), n = 3)[[3]]
4
5
6
> as.numeric(weights)
[1] 6
> cat(weighted.mean(data, weights))
Error in x * w : non-numeric argument to binary operator
答案 0 :(得分:1)
weighted.mean
不会将字符转换为数字。您只是将他们的as.numeric
输出打印到shell并忘记了weighted.mean
的两个参数是字符。