我对R的工作还很陌生,我希望有人能给我指出正确的方向。我有一个tible格式的数据集,我需要遍历每一行。 在每一行中,我必须检查3个列的集合。 i、 e如果其中一列的值为0,我必须删除所有三列并计算下三列。你知道吗
data_set <- as.data.frame(matrix(nrow=2))
data_set$Basket1<- c(45,35)
data_set$Type1 <- c("Normal","Premium")
data_set$Amount1 <- c(4,5)
data_set$Basket2 <- c(4,98)
data_set$Type2 <- c("Normal","Normal")
data_set$Amount2 <- c(0,4)
#when Type is "Premium" I want to remove the values for
#Basket1,Type1,Amount1
#and shift the next 3 cells to the left
我强烈建议不要考虑将值向左或向右移动—这并没有充分利用R的数据帧对象,在这些对象中,列应该被视为具有完整性。因此,我认为应该根据需要的逻辑在右侧添加新列,然后(如果需要)删除所有原始列,而不是移动和删除单元格。有一种方法可以做到这一点,即创建新的amount、basket和type列,并在末尾丢弃其余的列:
请看我的更新,在最后的基础上,你添加了新的例子。你知道吗
您可以这样做:
在新示例中,我们有一些非数字列。我们要做的唯一改变是先检查它们是否是数字。你知道吗
根据我之前回答的评论中的讨论,这里有另一种方法,它可以避免事先不知道列的数量。在这种情况下,首先将数据转换成一个已知的形状总是值得的,在这种情况下,它只能是一个细长的形状。一旦处于这种状态,就可以按客户id对其进行分组,并以这种方式执行任何需要的操作:
这将返回:
这种方法取决于它们在如何标记原始列方面的结构;例如,它们是按列集编号的,并且列名中没有任何其他数字。你知道吗
相关问题 更多 >
编程相关推荐