警告数值表达式具有> 1元素:仅第一个使用 [英] Warning numerical expression has >1 elements: only the first used
问题描述
我有一个数据集,如下所示:
Apr May Jun Jul Aug Sep Oct Nov b
1.0 9.0 4.0 5.3 6.4 3.4 2.5 4.3 2
5.0 6.0 9.0 2.3 5.8 2.3 6.5 5.2 3
8.0 4.0 6.0 0.7 5.2 1.2 2.2 6.1 4
2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 7
3.2 3.2 3.2 3.2 3.2 3.2 3.2 3.2 8
4.4 4.1 5.1 6.1 7.1 8.1 9.1 6.8 6
5.6 5.0 3.2 4.2 5.2 1.2 2.2 3.2 5
6.8 5.9 8.9 2.3 3.3 5.7 4.7 3.7 5
8.0 6.8 9.8 4.8 5.8 6.8 7.8 8.8 5
9.2 7.7 7.7 2.8 3.8 4.8 5.8 6.8 6
我想添加列总和data$sum=rowSums(data[data$b:8])
.但是得到一个警告`数字表达式有2124个元素:仅第一个使用.请让我知道一种更好的方法.
以下是基于您的评论的解决方案:
data$sum <- NA # important to create the column before the for loop
for (rowIdx in 1:nrow(data)) {
startCol <- data[rowIdx, "b"]
data[rowIdx, "sum"] <- sum(data[rowIdx, startCol:8])
}
您需要使用for循环/Apply语句来实现此目的,因为您无法使用[
子集运算符为每行指定不同的起始列.
当您使用[]
而不使用逗号时,可能会发生两件事,具体取决于您的数据结构:
-
如果
data
是matrix
,则它将整个矩阵视为单个向量,其中每一列接一个出现.例如,data[1:15]
将在"Apr"列中返回10个值,然后在"May"列中返回前5个值. -
如果
data
是data.frame
,它将使用索引查找列.即data[1:5]
与data[,1:5]
相同.原因是data.frame
实际上是引擎盖下的list()
,其中每一列都是list()
的元素.
I have a dataset as follows:
Apr May Jun Jul Aug Sep Oct Nov b
1.0 9.0 4.0 5.3 6.4 3.4 2.5 4.3 2
5.0 6.0 9.0 2.3 5.8 2.3 6.5 5.2 3
8.0 4.0 6.0 0.7 5.2 1.2 2.2 6.1 4
2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 7
3.2 3.2 3.2 3.2 3.2 3.2 3.2 3.2 8
4.4 4.1 5.1 6.1 7.1 8.1 9.1 6.8 6
5.6 5.0 3.2 4.2 5.2 1.2 2.2 3.2 5
6.8 5.9 8.9 2.3 3.3 5.7 4.7 3.7 5
8.0 6.8 9.8 4.8 5.8 6.8 7.8 8.8 5
9.2 7.7 7.7 2.8 3.8 4.8 5.8 6.8 6
I want to add a column sum data$sum=rowSums(data[data$b:8])
. But getting a warning `numerical expression has 2124 elements: only the first used. Please let me know a better method.
Here's a solution based on your comments:
data$sum <- NA # important to create the column before the for loop
for (rowIdx in 1:nrow(data)) {
startCol <- data[rowIdx, "b"]
data[rowIdx, "sum"] <- sum(data[rowIdx, startCol:8])
}
You need to use a for loop / apply statement to achieve this because you cannot specify a different starting column for each row using the [
subset operator.
Two things can happen when you use []
without a comma depending on your data structure:
If
data
is amatrix
it will treat the entire matrix as a single vector, where each column occurs one after another. For example,data[1:15]
will return the 10 values in the "Apr" column then the first 5 values in the "May" column.If
data
is adata.frame
it will use the indices to look up columns. That isdata[1:5]
is the same asdata[,1:5]
. The reason for this is that adata.frame
is really alist()
underneath the hood, where each column is an element of thelist()
.
这篇关于警告数值表达式具有> 1元素:仅第一个使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!