【发布时间】:2016-08-09 09:59:44
【问题描述】:
我必须调整一个代码,它可以完美地与不同的 data.frame 但条件相似。
这是我的 data.frame 的示例:
df <- read.table(text = 'ID Day Count
33012 9526 4
35004 9526 4
37006 9526 4
37008 9526 4
21009 1913 3
24005 1913 3
25009 1913 3
22317 2286 2
37612 2286 2
25009 14329 1
48007 9527 0
88662 9528 0
1845 9528 0
8872 2287 0
49002 1914 0
1664 1915 0', header = TRUE)
我需要在我的 data.frame 中添加一个新列 (new_col),其中包含从 1 到 4 的值。这些 new_col 值必须包括每一天 (x) 天 (x +1)和天 (x +2),其中 x = 9526、1913、2286、14329(列 Day)。
我的输出应该如下:
ID Day Count new_col
33012 9526 4 1
35004 9526 4 1
37006 9526 4 1
37008 9526 4 1
21009 1913 3 2
24005 1913 3 2
25009 1913 3 2
22317 2286 2 3
37612 2286 2 3
25009 14329 1 4
48007 9527 0 1
88662 9528 0 1
1845 9528 0 1
8872 2287 0 3
49002 1914 0 2
1664 1915 0 2
new_col 排序的 data.frame 将是:
ID Day Count new_col
33012 9526 4 1
35004 9526 4 1
37006 9526 4 1
37008 9526 4 1
48007 9527 0 1
88662 9528 0 1
1845 9528 0 1
21009 1913 3 2
24005 1913 3 2
25009 1913 3 2
49002 1914 0 2
1664 1915 0 2
22317 2286 2 3
37612 2286 2 3
8872 2287 0 3
25009 14329 1 4
我的真实 data.frame 比示例更复杂(即Count 列中有更多列和更多值)。
@mrbrick 在我之前的问题 (Add column to dataframe depending on specific row values) 中建议我的代码如下:
x <- c(1913, 2286, 9526, 14329)
df$new_col <- cut(df$Day, c(-Inf, x, Inf))
df$new_col <- as.numeric(factor(df$new_col, levels=unique(df$new_col)))
但它仅适用于第 x 天、第 x 天 -1 和第 x -2 天。
任何建议都会很有帮助。
【问题讨论】:
-
在剪切命令中尝试
df$new_col <- cut(df$Day, c(-Inf, x, Inf), right=F)。 -
您还有更多
df$Day的值吗?属于不同组的值是否总是彼此相距很远? -
你知道
Day列中所有你想要的x吗?