我有一个名为New的数据框。使用此数据帧,我需要使用for循环和if-else条件创建数据帧
新数据框如下
no mode start end
1 S 0.026 33.059
2 T 33.176 38.057
3 S 38.202 40.082
4 T 40.145 51.160
5 S 51.272 52.254
6 T 52.274 56.238
7 S 56.359 57.259
8 T 57.396 62.280
9 S 62.454 69.270
,所需的数据框应采用以下格式 即如果模式“ S”且其差值为<= 1(结束开始),
no mode start end
1 S 0.026 33.059
2 T 33.176 38.057
3 S 38.202 40.082
4 T 40.145 62.280
5 S 62.454 69.270
为此,我正在使用以下代码
mode <- 0
start <- 0
end <- 0
abc <- data.frame(mode, start, end)
for (i in 1:nrow(New)) {
if((New[i,2] = "S" && New[i,4]-New[i,3])>1) abc$mode[i] = New[i,2]
else
abc$mode[i] = New[i-1,2]
if((New[i,2] = "S" && New[i,4]-New[i,3])>1) abc$start[i] = New[i,3]
else
abc$start[i] = New[i-1,3]
if((New[i,2] = "S" && New[i,4]-New[i,3])>1) abc$end[i] = New[i,4]
else
abc$end[i] = New[i,4]
}
我遇到以下错误
Error in "S" && New[i, 4] - New[i, 3] : invalid 'x' type in 'x && y'
预先感谢
答案 0 :(得分:0)
我认为您可以消除循环和if
s
New <- read.table(text="
no mode start end
1 S 0.026 33.059
2 T 33.176 38.057
3 S 38.202 40.082
4 T 40.145 51.160
5 S 51.272 52.254
6 T 52.274 56.238
7 S 56.359 57.259
8 T 57.396 62.280
9 S 62.454 69.270",
header=TRUE, stringsAsFactors=FALSE)
abc <- New[New$mode == "S" & New$end - New$start <= 1, ]
abc
# no mode start end
# 5 5 S 51.3 52.3
# 7 7 S 56.4 57.3