我对R相当陌生,看起来这应该很简单,但我的搜索一无所获。
我有一些数据在Excel中格式化为一系列列表-即:第1行包含类别,项目如下所示:
Fruit Vegetable Grain Meat
1 Apple Carrot Wheat Chicken
2 Grape Potato Rice Beef
3 Banana Barley Pork
4 Orange
5 Kiwi
字符串
我想把它变成一个长的 Dataframe ,列名变成这样的类别:
Category Food
1 Fruit Apple
2 Fruit Grape
3 Fruit Banana
4 Fruit Orange
5 Fruit Kiwi
6 Vegetable Carrot
7 Vegetable Potato
8 Grain Wheat
9 Grain Rice
10 Grain Barley
11 Meat Chicken
12 Meat Beef
13 Meat Pork
型
下面是输入数据:
df <- structure(list(Fruit = c("Apple", "Grape", "Banana", "Orange",
"Kiwi"), Vegetable = c("Carrot", "Potato", NA, NA, NA), Grain = c("Wheat",
"Rice", "Barley", NA, NA), Meat = c("Chicken", "Beef", "Pork",
NA, NA)), row.names = c(NA, -5L), class = c("tbl_df", "tbl",
"data.frame"))
型
我觉得我应该使用tidyr::pivot_longer(),但不太清楚如何使用。
任何建议赞赏!
1条答案
按热度按时间fruv7luv1#
为了给评论中给出的想法添加一些肉,下面是你应该如何做到的:
字符串
我更喜欢保罗的回答,但两者都行得通