【发布时间】:2014-12-19 10:45:36
【问题描述】:
我在 data.frame 中有一个列,其中每个观察值都是一串数字(例如“1,5,6,7,0,21”)。我正在尝试计算非连续数字的第一个实例的差异。在上面的示例中,结果将是5 - 1 = 4。但是,使用我目前拥有的代码,我得到了6。如果我的输入是“1,2,0,21”,我会得到21 - 2 = 19 的正确结果(在减法发生之前对数字进行排序)。我想也许零是问题所在,但在所有值上加一并不能解决问题。也许我的索引有问题?有什么建议?
# find distance between number in first gap of non-consecutive numbers
b <- c("1,5,6,7,0,21") # does not work as desired result is 6 instead of 4
# b <- ("1,2,0,21") # works as desired
b.Uncomma <- sort(unique(as.numeric(unlist(strsplit(b, split=","))))) # remove commas, remove duplicates, sort
#b.Uncomma <- b.Uncomma + 1 # same result
b.Gaps <- c(which(diff(b.Uncomma) != 1), length(b.Uncomma)) # find where the difference is not 1
b.FirstGap <- b.Gaps[1:2] # get the positions/index on either side of the first gap
b.Result <- b.Uncomma[(b.FirstGap[2])] - b.Uncomma[(b.FirstGap[1])] # subtract to get result
【问题讨论】:
-
在 'c("1,2,0,21")' 中,非连续数字的第一个实例不是 2, 0 吗?给你 0 - 2 = -2 ?
-
是的,我认为需要添加更准确的解释。
-
@epwalsh 我猜它可能是
sort之后的那个 -
这就是我的想法:
diff(x)[which(diff(x) != 1)[1]]其中x是你的b.Uncomma -
@epwalsh 这以更少的代码行数实现了预期的结果。为了便于理解,
diff(x)查找条目之间的差异,[which(diff(x) != 1)[1]]查找不连续数字的第一个实例。