r - R - 根据前后值清理数据
问题描述
我有一张表格,后来根据多个条件分为多个间隔。在极少数情况下,我的一行或多行不属于定义的间隔,因此我想对数据进行一些额外的清理。
对于每个组(名称,位置),如果停止中的行值 == 0,我需要计算这些行中有多少在间隔中。如果小于<3,我需要检查有多少连续行是市场作为停止== 1 高于和低于具有零值的区间。如果停止 == 1 以上和以下 == 1 的值计数,那么我需要将间隔中的值更改为 0 到 1。
我希望图片能更清楚:
df <- read.table(text="name location stop
John London 1
John London 1
John London 1
John London 1
John London 1
John London 1
John London 1
John London 0
John London 0
John London 1
John London 1
John London 1
John London 1
John London 1
John London 1
John London 0
John New_York 0
John New_York 0
John New_York 0
John New_York 1
John New_York 0
",header = TRUE, stringsAsFactors = FALSE)
解决方案
您可以遍历行,但似乎您想要做的就是替换101
with111
和1001
with 1111
in的所有实例stop
。您可以通过将stop
列转换为字符串来执行此操作,然后使用以下命令进行替换gsub()
:
stopString = paste0(df$stop, collapse = "")
stopString = gsub("101","111",stopString)
stopString = gsub("1001","1111",stopString)
df$stop = as.numeric(unlist(strsplit(stopString,"")))
> df
name location stop
1 John London 1
2 John London 1
3 John London 1
4 John London 1
5 John London 1
6 John London 1
7 John London 1
8 John London 1
9 John London 1
10 John London 1
11 John London 1
12 John London 1
13 John London 1
14 John London 1
15 John London 1
16 John London 0
17 John New_York 0
18 John New_York 0
19 John New_York 0
20 John New_York 1
21 John New_York 0
编辑:按名称和位置分组:
df <- read.table(text="name location stop
John London 1
John London 0
John London 1
John New_York 0
John New_York 1
John New_York 0
John New_York 0
John New_York 0
John New_York 1
John New_York 0
",header = TRUE, stringsAsFactors = TRUE)
f <- function(x)
{
stopString = paste0(x, collapse = "")
stopString = gsub("101","111",stopString)
stopString = gsub("1001","1111",stopString)
as.numeric(unlist(strsplit(stopString,"")))
}
> df %>% dplyr::group_by(name, location) %>%
dplyr::summarise(stop=stop, s=f(stop))
# A tibble: 10 x 4
# Groups: name, location [2]
name location stop s
<fct> <fct> <int> <dbl>
1 John London 1 1
2 John London 0 1
3 John London 1 1
4 John New_York 0 0
5 John New_York 1 1
6 John New_York 0 0
7 John New_York 0 0
8 John New_York 0 0
9 John New_York 1 1
10 John New_York 0 0
推荐阅读
- ruby-on-rails - RSpec 测试单独通过,整个套件失败
- xml - 将具有西里尔字符的数据帧写入 HDFS 正在更改编码
- dart - 如何在组中创建 ListView?
- codeigniter - 在codeigniter中打印带有条形码的表格的pdf
- linux - 在 Debian 控制台中将 Active 设置为 FALSE 时,带有 TIdServerIOHandlerSSLOpenSSL 的 TIdHTTPServer 不会返回
- javascript - CKEditor 4 和 ExtJS 6.7.0 集成弹出窗口问题
- git - git clone 拉取请求而不是主分支
- vb.net - vb how to find a string in a string and return the string into a variable
- reactjs - “字符串”类型上不存在属性“过滤器”
- android - 在我的手机上安装apk文件时出现问题