在 R 中重构字符串
restructure character-string in R
我有以下测试数据框。变量 times
显示一个人在问卷中回答不同问题(例如 f140、f130、f210 等)所需的秒数。
示例:人 1
有 4 秒回答问题 f140
,10 秒回答问题 130
等。问卷中的问题是随机的,问题总数可能会有所不同.
df <- data.frame(user = 1:4,
times = c(
"f140:4,f130:10,f110:3,f120:3,f210:5,f220:4,f240:5,f230:4,f300:4,f410:9,f420:4,f450:18,f500:64,",
"f120:4,f110:3,f140:7,f130:17,f240:10,f230:6,f220:4,f210:4,f300:6,f410:12,f420:10,f450:38,f500:42,",
"f130:26,f120:8,f140:5,f110:4,f220:5,f210:6,f230:9,f240:5,f300:8,f410:8,f420:5,f450:30,f500:3,",
"f120:9,f130:13,f110:5,f140:11,f210:8,f220:12,f240:7,f230:10,f300:8,f410:10,f420:8,f450:46,f500:111,"
)
)
如何以这样的形式获取这些数据:
user | question | time | order
1 f140 4 1
1 f130 10 2
...
2 f120 4 1
2 f110 3 2
...
我尝试使用 separate()
,但到目前为止失败了。感谢您的帮助!
这可以帮助:
library(dplyr)
library(tidyr)
#Code
new <- df %>%
separate_rows(times,sep = ',') %>%
separate(times,c('question','times'),sep=':') %>%
filter(!is.na(times)) %>%
group_by(user) %>%
mutate(order=row_number())
输出:
# A tibble: 52 x 4
# Groups: user [4]
user question times order
<int> <chr> <chr> <int>
1 1 f140 4 1
2 1 f130 10 2
3 1 f110 3 3
4 1 f120 3 4
5 1 f210 5 5
6 1 f220 4 6
7 1 f240 5 7
8 1 f230 4 8
9 1 f300 4 9
10 1 f410 9 10
# ... with 42 more rows
我有以下测试数据框。变量 times
显示一个人在问卷中回答不同问题(例如 f140、f130、f210 等)所需的秒数。
示例:人 1
有 4 秒回答问题 f140
,10 秒回答问题 130
等。问卷中的问题是随机的,问题总数可能会有所不同.
df <- data.frame(user = 1:4,
times = c(
"f140:4,f130:10,f110:3,f120:3,f210:5,f220:4,f240:5,f230:4,f300:4,f410:9,f420:4,f450:18,f500:64,",
"f120:4,f110:3,f140:7,f130:17,f240:10,f230:6,f220:4,f210:4,f300:6,f410:12,f420:10,f450:38,f500:42,",
"f130:26,f120:8,f140:5,f110:4,f220:5,f210:6,f230:9,f240:5,f300:8,f410:8,f420:5,f450:30,f500:3,",
"f120:9,f130:13,f110:5,f140:11,f210:8,f220:12,f240:7,f230:10,f300:8,f410:10,f420:8,f450:46,f500:111,"
)
)
如何以这样的形式获取这些数据:
user | question | time | order
1 f140 4 1
1 f130 10 2
...
2 f120 4 1
2 f110 3 2
...
我尝试使用 separate()
,但到目前为止失败了。感谢您的帮助!
这可以帮助:
library(dplyr)
library(tidyr)
#Code
new <- df %>%
separate_rows(times,sep = ',') %>%
separate(times,c('question','times'),sep=':') %>%
filter(!is.na(times)) %>%
group_by(user) %>%
mutate(order=row_number())
输出:
# A tibble: 52 x 4
# Groups: user [4]
user question times order
<int> <chr> <chr> <int>
1 1 f140 4 1
2 1 f130 10 2
3 1 f110 3 3
4 1 f120 3 4
5 1 f210 5 5
6 1 f220 4 6
7 1 f240 5 7
8 1 f230 4 8
9 1 f300 4 9
10 1 f410 9 10
# ... with 42 more rows