I have a data frame called New. using this data frame, I need to create a data frame using for loop and if-else condition
the New data frame is as follows
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
and the required data frame should be in the following form ie if mode "S" and its difference is <=1 (end-start),
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
for this, I am using the following code,
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]
}
i am getting the following error
Error in "S" && New[i, 4] - New[i, 3] : invalid 'x' type in 'x && y'
thanks in advance
I think you can do away with the loop and the 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.