gpt4 book ai didi

R 根据值拆分列

转载 作者:行者123 更新时间:2023-12-01 09:37:58 24 4
gpt4 key购买 nike

我有以下数据,我想计算总分钟数,我想知道是否可以将一列分为两列,一列中的分钟数和另一列中的秒数?

> q
time
1 0m 22s
2 1m 7s
3 3m 35s
4 11m 43s
5 1m 8s
6 2m 21s
7 9m 33s
8 0m 56s
9 0m 2s
10 0m 2s
11 0m 50s
12 0m 25s
13 0m 33s
14 2m 26s
15 0m 20s
16 1m 47s
17 0m 36s
18 0m 3s
19 0m 2s
20 0m 5s

==>给予:

> q
min seconds
1 0 22
2 1 7

最佳答案

我对日期不太熟悉,但您可以查看函数 as.Datestrptime。使用你的 data.frame:

df <- data.frame(time = c("0m 22s", "1m 7s", "3m 35s", "11m 43s", "1m 8s", "2m 21s", "9m 33s", "0m 56s", "0m 2s", "0m 2s", "0m 50s", "0m 25s", "0m 33s", "2m 26s", "0m 20s", "1m 47s", "0m 36s", "0m 3s", "0m 2s", "0m 5s"))

df$time.2 <- strptime(df$time, "%Mm %Ss")

现在可以选择具体的值了,看看就行了

attributes(df[, "time.2"])

并分配

df$min <- df[, "time.2"][["min"]]
df$sec <- df[, "time.2"][["sec"]]

这给出了:

R> df
time time.2 min sec
1 0m 22s 2010-12-02 00:00:22 0 22
2 1m 7s 2010-12-02 00:01:07 1 7
3 3m 35s 2010-12-02 00:03:35 3 35
4 11m 43s 2010-12-02 00:11:43 11 43
5 1m 8s 2010-12-02 00:01:08 1 8
6 2m 21s 2010-12-02 00:02:21 2 21
7 9m 33s 2010-12-02 00:09:33 9 33
8 0m 56s 2010-12-02 00:00:56 0 56
9 0m 2s 2010-12-02 00:00:02 0 2
10 0m 2s 2010-12-02 00:00:02 0 2
11 0m 50s 2010-12-02 00:00:50 0 50
12 0m 25s 2010-12-02 00:00:25 0 25
13 0m 33s 2010-12-02 00:00:33 0 33
14 2m 26s 2010-12-02 00:02:26 2 26
15 0m 20s 2010-12-02 00:00:20 0 20
16 1m 47s 2010-12-02 00:01:47 1 47
17 0m 36s 2010-12-02 00:00:36 0 36
18 0m 3s 2010-12-02 00:00:03 0 3
19 0m 2s 2010-12-02 00:00:02 0 2
20 0m 5s 2010-12-02 00:00:05 0 5

编辑:由于您只想拆分 data.frame 以便能够计算总分钟数,因此您甚至不需要创建新列 minsec 和可以简单地使用列 time.2。这两步就够了

df$time.2 <- strptime(df$time, "%Mm %Ss")
sum(df[, "time.2"][["min"]])

R> [1] 30

关于R 根据值拆分列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4338620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com