如何确定列表中的最终数字是偶数还是奇数,然后将该行放入数据框中。
我有多个以奇数或偶数“圈数”(即下面的#17和26)结尾的csv文件
Total time 10:00.61
Lap times
01 00:07.46
02 00:05.64
03 00:01.07
04 00:01.04
05 00:04.71
06 00:06.43
07 00:12.52
08 00:07.34
09 00:05.46
10 00:05.81
11 00:05.52
12 00:06.51
13 00:10.75
14 00:00.83
15 00:03.64
16 00:02.75
17 00:01.20
还有这个...
Total time 10:00.61
Lap times
01 00:07.46
02 00:05.64
03 00:01.07
04 00:01.04
05 00:04.71
06 00:06.43
07 00:12.52
08 00:07.34
09 00:05.46
10 00:05.81
11 00:05.52
12 00:06.51
13 00:10.75
14 00:00.83
15 00:03.64
16 00:02.75
17 00:01.20
18 00:06.17
19 00:04.40
20 00:00.75
21 00:00.84
22 00:01.29
23 00:02.31
24 00:03.04
25 00:02.85
26 00:05.86
我使用此循环浏览csv文件
output = lapply(files, function(x) {
dat = read.csv(x, header= TRUE)
dat = dat[-c(1),]
dat = as.data.frame(dat)
dat = separate(data = dat, col = dat, into = c("lap", "duration"), sep =
"\\ ")
})
输出看起来像这样
[[1]]
lap duration
1 01 00:07.46
2 02 00:05.64
3 03 00:01.07
4 04 00:01.04
5 05 00:04.71
6 06 00:06.43
7 07 00:12.52
8 08 00:07.34
9 09 00:05.46
10 10 00:05.81
11 11 00:05.52
12 12 00:06.51
13 13 00:10.75
14 14 00:00.83
15 15 00:03.64
16 16 00:02.75
17 17 00:01.20
[[2]]
lap duration
1 01 00:07.46
2 02 00:05.64
3 03 00:01.07
4 04 00:01.04
5 05 00:04.71
6 06 00:06.43
7 07 00:12.52
8 08 00:07.34
9 09 00:05.46
10 10 00:05.81
11 11 00:05.52
12 12 00:06.51
13 13 00:10.75
14 14 00:00.83
15 15 00:03.64
16 16 00:02.75
17 17 00:01.20
18 18 00:06.17
19 19 00:04.40
20 20 00:00.75
21 21 00:00.84
22 22 00:01.29
23 23 00:02.31
24 24 00:03.04
25 25 00:02.85
26 26 00:05.86
如何查看最后一行是偶数还是奇数(分别是第17和26行)?然后,我可能想将这些最后几行放入一个单独的数据框中。
答案 0 :(得分:1)
首先,您可以使读取过程变得非常简单。
output <- lapply(files, read.csv, skip = 1)
现在,行数为奇数/偶数。
n <- sapply(output, nrow)
ifelse(n %% 2 == 0, "even", "odd")
请注意,您可以让"even"
返回您选择的任何内容,而不是字符值"odd"
和ifelse
。
答案 1 :(得分:0)
尚未测试,但这可以给您一些提示。只需对您的代码进行一些修改:
output = lapply(files, function(x) {
dat = read.csv(x, header= TRUE)
last_row = nrow(dat)
# to see if even or odd number
ifelse(last_row %% 2==0, 'this is even','this is odd')
# insert last row into a new data frame
last_row_values = unlist(dat[last_row,])
dat = as.data.frame(last_row_values)
colnames(dat) <- c('lap','duration')
return (dat)
})
我认为由于output
是列表,以后您可能需要这样做:
df = do.call('rbind', output)