下面是一些示例数据。每一行都是不同的参与者。每个参与者完成五次试验。在每次试验中,他们从一组 10 个水果中挑选一个水果(不更换)。
ID | 试用_1 | 试用_2 | 试用_3 | 试用_4 | 试用_5 |
---|---|---|---|---|---|
01 | 苹果 | 橘子 | 香蕉 | 桃 | 葡萄 |
02 | 葡萄 | 西瓜 | 芒果 | 桃 | 杏 |
03 | 梨 | 葡萄 | 芒果 | 橘子 | 香蕉 |
04 | 西瓜 | 苹果 | 桃 | 葡萄 | 梨 |
05 | 香蕉 | 桃 | 苹果 | 葡萄 | 芒果 |
我想创建 10 个新列——每个水果一个——其中包含试用号(如果没有试用号,则为“NA”):
ID | 试用_1 | 试用_2 | 试用_3 | 试用_4 | 试用_5 | 苹果 | 杏 | 香蕉 | 葡萄 | 芒果 | 橘子 | 桃 | 梨 | 草莓 | 西瓜 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01 | 苹果 | 橘子 | 香蕉 | 桃 | 葡萄 | 1 | 不适用 | 3 | 5 | 不适用 | 2 | 4 | 不适用 | 不适用 | 不适用 |
02 | 葡萄 | 西瓜 | 芒果 | 桃 | 杏 | 不适用 | 5 | 不适用 | 1 | 3 | 不适用 | 4 | 不适用 | 不适用 | 2 |
03 | 梨 | 葡萄 | 芒果 | 橘子 | 香蕉 | 不适用 | 不适用 | 5 | 2 | 3 | 4 | 不适用 | 1 | 不适用 | 不适用 |
04 | 西瓜 | 苹果 | 桃 | 葡萄 | 梨 | 2 | 不适用 | 不适用 | 4 | 不适用 | 不适用 | 3 | 5 | 不适用 | 1 |
05 | 香蕉 | 桃 | 苹果 | 葡萄 | 芒果 | 3 | 不适用 | 1 | 4 | 5 | 不适用 | 2 | 不适用 | 不适用 | 不适用 |
我可以像这样为每个水果列这样做,但它看起来很笨重:
mutate(apple = ifelse(trial_1 == "apple", 1,
ifelse(trial_2 == "apple", 2,
ifelse(trial_2 == "apple", 3,
ifelse(trial_2 == "apple", 4
ifelse(trial_2 == "apple", 5, "NA"))))))
我认为有一个更简单、更简洁的解决方案,可能rowwise()
用于匹配水果名称,然后只返回列名称的最后一个字符(即数字)。但我就是无法解决。你能帮忙吗?
library(tidyverse)
df %>%
pivot_longer(-ID) %>%
mutate(name = parse_number(name)) %>%
pivot_wider(names_from = value, values_from = name)
这将给出右侧的列。要将这些附加到原始文件中,
left_join(df,
# the code above
)
结果
Joining, by = "ID"
# A tibble: 5 x 15
ID trial_1 trial_2 trial_3 trial_4 trial_5 apple orange banana peach grapes watermelon mango apricot pear
<chr> <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 01 apple orange banana peach grapes 1 2 3 4 5 NA NA NA NA
2 02 grapes watermelon mango peach apricot NA NA NA 4 1 2 3 5 NA
3 03 pear grapes mango orange banana NA 4 5 NA 2 NA 3 NA 1
4 04 watermelon apple peach grapes pear 2 NA NA 3 4 1 NA NA 5
5 05 banana peach apple grapes mango 3 NA 1 2 4 NA 5 NA NA
源数据:
tibble::tribble(
~ID, ~trial_1, ~trial_2, ~trial_3, ~trial_4, ~trial_5,
"01", "apple", "orange", "banana", "peach", "grapes",
"02", "grapes", "watermelon", "mango", "peach", "apricot",
"03", "pear", "grapes", "mango", "orange", "banana",
"04", "watermelon", "apple", "peach", "grapes", "pear",
"05", "banana", "peach", "apple", "grapes", "mango"
) -> df
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句