在R中,我想通过对值进行装箱并使用每个箱中的值的数量(总和)来对数据帧的每一行进行分类,以通过使用if-else逻辑将它们分为2组(类)。
首先,我创建了一个数据框x:
n1 <- c(1, 7); n2 <- c(2, 11); n3 <- c(10, 14); n4 <- c(23, 32); n5 <- c(37, 37); n6 <- c(45, 41)
x <- data.frame(n1, n2, n3, n4, n5, n6)
x
n1 n2 n3 n4 n5 n6
1 1 2 10 23 37 45
2 7 11 14 32 37 41
第一行应归类为“ P”,因为它有1对值(1、2)落在同一个容器1..10中。
第二行应归类为“ PP”,因为它有2对值(11、14和32、37)分别落入2个档位:10..19和30..39。
因此,在创建数据框x之后,我创建了一个for循环:
for(i in nrow(x)){
# binning the data:
bins <- split(as.numeric(x[i, ]), cut(as.numeric(x[i, ]), c(0, 9, 19, 29, 39, 49)))
# creating the rule for p (1 pair of numbers falling in the same range)
p <- (sum(lengths(bins) == 2) == 1 & sum(lengths(bins) == 1) == 4)
# creating the rule for pp (2 different pairs, each has 2 numbers falling in the same range)
pp <- (sum(lengths(bins) == 2) == 2 & sum(lengths(bins) == 1) == 2 & sum(lengths(bins) == 0) == 1)
if(p){
x$types <- "P"
} else if(pp){
x$types <- "PP"
} else{
stop("error")
}
}
print(x)
我想创建一个新的名为type的列,其中包含类P或PP:
n1 n2 n3 n4 n5 n6 types
1 1 2 10 23 37 45 P
2 7 11 14 32 37 41 PP
相反,代码仅返回PP:
n1 n2 n3 n4 n5 n6 types
1 1 2 10 23 37 45 PP
2 7 11 14 32 37 41 PP
这是因为循环在行上运行两次。但是,如果仅运行一次,则所有行都将分类为“ P”,而不是“ PP”。我希望这很简单,但到目前为止还无法弄清楚。
for
循环中的错误是i
分配时不使用type
。x$types <- "P"
将整个types
列分配为"P"
。x$types <- "PP"
将整个types
列分配为"PP"
。因此,无论最后结果是什么,这将是整个列的值。
另外,在添加列之后使用完整的行 x[i, ]
是很危险的types
。大概您不想尝试将“ P”和“ PP”值转换types
为数字并将它们进行装箱。我建议创建types
一个单独的向量,并仅在循环后将其添加为列。循环之前:types <- chracter(nrow(x))
。循环内:types[i] <-
而不是x$types <-
。循环后,x$types <- types
。
您还犯了for (i in nrow(x))
when时的经典语法错误for (i in 1:nrow(x))
。
解决所有这些问题:
n1 <- c(1, 7); n2 <- c(2, 11); n3 <- c(10, 14); n4 <- c(23, 32); n5 <- c(37, 37); n6 <- c(45, 41)
x <- data.frame(n1, n2, n3, n4, n5, n6)
types <- character(nrow(x))
for(i in 1:nrow(x)){
# binning the data:
bins <- split(as.numeric(x[i, ]), cut(as.numeric(x[i, ]), c(0, 9, 19, 29, 39, 49)))
# creating the rule for p (1 pair of numbers falling in the same range)
p <- (sum(lengths(bins) == 2) == 1 & sum(lengths(bins) == 1) == 4)
# creating the rule for pp (2 different pairs, each has 2 numbers falling in the same range)
pp <- (sum(lengths(bins) == 2) == 2 & sum(lengths(bins) == 1) == 2 & sum(lengths(bins) == 0) == 1)
if(p){
types[i] <- "P"
} else if(pp){
types[i] <- "PP"
} else{
stop("error")
}
}
x$types <- types
x
# n1 n2 n3 n4 n5 n6 types
# 1 1 2 10 23 37 45 P
# 2 7 11 14 32 37 41 PP
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句